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 out, 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 that all fields have been filled in, you should enable the button when one of the fields loses focus through the addEventListener()
function.
We can enable the button for example when the last field loses focus and the entire form is validated. Here's the example:
document.querySelector('.ultimo').addEventListener('blur', function(){
if(formularioValido()){
document.querySelector('.meu-botao').removeAttribute('disabled');
}
});
The function formularioValido()
is used to verify that all fields have been correctly filled in.
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 to this code. Use it as an example to create what best fits your situation. I made an example in codepen
. You can see this link here
Success (+