HTML:
<form>
<input type="text" />
<input type="text" />
<input type="text" class="ultimo"/>
<button disabled class="meu-botao">Enviar</button>
</form>
CSS:
input
{
display:block;
margin-bottom:15px;
height:30px;
}
.valido
{
border:1px solid green;
}
The first thing to do is validate if all fields have been filled in, which can be done as follows:
var input = document.querySelectorAll('input');
for(i = 0; i < input.length; i++){
input[i].addEventListener('blur', function(){
if(this.value != ''){
this.classList.add('valido');
}
});
}
After validating if all fields have been filled you must enable the button when one of the fields loses focus through the function addEventListener()
.
We can enable the button for example when the last field loses focus and the whole form is validated. Follow the example:
document.querySelector('.ultimo').addEventListener('blur', function(){
if(formularioValido()){
document.querySelector('.meu-botao').removeAttribute('disabled');
}
});
The function formularioValido()
serves to verify that all fields have been correctly filled.
var formularioValido = function(){
var inputsValidos = 0;
for(i = 0; i < input.length; i++){
if(input[i].classList.contains('valido')){
inputsValidos++;
}
}
if(inputsValidos == input.length) return true;
else return false;
};
There are several improvements that can be made in this code. Use it as an example to create the one that best fits your situation. I made an example in codepen
. You can see in this link here
Success (+