Enable and Disable a [Closed]

1

Personal.

I'm developing a form with some mandatory inputs / fields, and below the fields, there is a button whose target / action given to it is only released if the fields are filled out. I would like to do the following thing:

If the inputs / fields were not already filled, the button was disabled, causing the user to not click and navigate to the destination / action given to the button. And as soon as the inputs were filled, the button was enabled, allowing the user to click.

Is there any way to do this? Thanks!

    
asked by anonymous 19.09.2016 / 00:39

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

    
19.09.2016 / 15:11