Enable and disable a button

Asked

Viewed 3,619 times

2

personal.

I am developing a form with some mandatory inputs/fields, and below the fields, there is a button, whose destination/action given(a) to it is only released if the fields are filled in. I’d like to do the following thing:

If the inputs/fields were not yet filled in, the button was disabled, causing the user not to click and navigate to the destination/action given(a) to the button. And once the inputs were filled, the button was enabled, allowing the user to click.

Is there any way to do this? Thank you!

1 answer

1

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 (+

Browser other questions tagged

You are not signed in. Login or sign up in order to post.