DEV Community

loading...
Cover image for You can block a button if a field is not filled with pure CSS

You can block a button if a field is not filled with pure CSS

Leandro RR
Brazilian dev always looking for learn new things and love for javascript and php
・2 min read

i'm doing this trick with just one field, if want add more fields, they need be direct childrens of <form>, and this will fail if you wrap the input field in another element.

HTML Structure

<form action="" class="form">
  <input type="text" class="form__input" placeholder="type your name..." required>
  <button class="form__button">submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

The CSS

:root {
  --success-color: #319E65;
  --error-color: #E8513B;
  --white-color: #FFFFFF;
  --silver-color: #BDC3C7;
  --light-color: #ECF0F1;
}

.form {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  max-width: 50%;
  margin: 0 auto;
}

.form__input {
  width: 100%;
  border-radius: 4px;
  border: 1px solid var(--silver-color);
  padding: 10px 20px;
  transition: all .3s ease-in-out;
}

.form__input:focus {
  outline: 0;
}

.form__button {
  background: var(--light-color);
  border-radius: 4px;
  border-style: solid;
  border-width: 1px;
  border-color: var(--silver-color);
  text-decoration: none;
  padding: 10px 20px;
  color: var(--silver-color);
  transition: all .3s ease-in-out;
  pointer-events: none;
  margin-left: 10px;
}

.form__input:invalid {
  border-color: var(--error-color);
}

.form__input:valid {
  border-color: var(--success-color);
}

.form__input:valid + button[class=form__button] {
  border-color: var(--success-color);
  background: var(--success-color);
  color: var(--white-color);
  cursor: pointer;
  pointer-events: initial; /* block click and events in this button */
}
Enter fullscreen mode Exit fullscreen mode

the trick here is :valid and :invalid, using it, you can validate the field, if empty :invalid will block it, if you type something, then :valid will make it clickable again at this line:

.form__input:valid + button[class=form__button] {
  border-color: var(--success-color);
  background: var(--success-color);
  color: var(--white-color);
  cursor: pointer;
  pointer-events: initial; /* the click event returns to the initial state */
}
Enter fullscreen mode Exit fullscreen mode

Result

Discussion (2)

Collapse
jonrandy profile image
Jon Randy • Edited

Form submission is blocked anyway by the very fact that the field isn't filled. Blocking clicking on the button is somewhat pointless since submission can still be initiated by pressing return. Greying it is a nice visual cue though.

Also, by blocking the clicking of the submission button, the user will be prevented from seeing the warning prompts telling them what's wrong with their input - unless they submitted by pressing return. This makes for a slightly confused, inconsistent UX