You can block a button if a field is not filled with pure CSS
Leandro RR
Posted on March 10, 2020
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>
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 */
}
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 */
}
Result
💖 💪 🙅 🚩
Leandro RR
Posted on March 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.