How to enable a button only when all inputs are completed?

Asked

Viewed 16,269 times

14

I have a <button> which is rendered as disabled(disabled) when page is initially loaded.

I’d like him to stay enabled(authorised) when all data are completed in <input>'s. How could I do this using jQuery?

  • Important to note, in addition to the answer given below by @Sergio, that your button already needs to be rendered with disabled applied, otherwise the user can click it before filling the form.

5 answers

13


The answer gets a little general without having specific code in the question.

But here’s a suggestion:

EDIT: I put a more modern version, the original version is down:

var inputs = $('input').on('keyup', verificarInputs);
function verificarInputs() {
    const preenchidos = inputs.get().every(({value}) => value)
    $('button').prop('disabled', !preenchidos);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
<input type="text" />
<button type="button" id="botao" disabled="disabled">Botão</button>


Original response:

// Mantém os inputs em cache:
var inputs = $('input');

// Chama a função de verificação quando as entradas forem modificadas
// Usei o 'keyup', mas 'change' ou 'keydown' são também eventos úteis aqui
inputs.on('keyup', verificarInputs);

function verificarInputs() {
    var preenchidos = true;  // assumir que estão preenchidos
    inputs.each(function () {
        // verificar um a um e passar a false se algum falhar
        // no lugar do if pode-se usar alguma função de validação, regex ou outros
        if (!this.value) {
          preenchidos = false;
          // parar o loop, evitando que mais inputs sejam verificados sem necessidade
          return false;
        }
    });
    // Habilite, ou não, o <button>, dependendo da variável:
    $('button').prop('disabled', !preenchidos); // 
}

Example

If a more advanced validation is needed I recommend using pluging for jQuery validations

  • Thanks Gustavo Rodrigues for the suggestions/comments :)

  • 3

    Cache, Event delegates... It’s all there. Excellent high-level technical solution. Greetings!

  • +1 Very good answer, I would do very similar, but I would use the Array.prototype.every only that would have to explain to the user that in old browsers need a Shim, filled variable would be the result of Every.

  • Would have a way to do with select?

  • Internet does not work

3

Try something like this, for example:

$(document).ready(function (){
    validate();
    $('#nome, #email, #telefone').change(validate);
});

function validate(){
    if ($('#nome').val().length > 0 &&
        $('#email').val().length > 0 &&
        $('#telefone').val().length > 0) {
        $("input[type=submit]").prop("disabled", false);
    }
    else {
        $("input[type=submit]").prop("disabled", true);
    }
}

Validation occurs when you take the focus off the field.

Jsfiddle

  • Thanks Paul! Exactly that.

  • 2

    Its function is dependent on the form structure... A better approach can be seen in the @Sergio response, because it is totally independent of how the form was built, as well as respecting cache, etc. Still, elegant solution.

  • @Tiagocésaroliveira Perfect, thanks for the tip!

3

I implemented a solution that works with input, textarea and select. I will iterate the elements just once on page-load, and assign events that might change the value of an input, textarea or select: change keyup mouseup.

Script

$(function () {
    // vou pegar apenas os controles que estiverem dentro do form especificamente
    // pois podem haver mais outros forms ou controles em outros locais, os quais
    // não desejo afetar
    var $inputs = $("input, textarea, select", "#formName"),
        $button = $("#botao");

    var limpos = 0;

    // contagem inicial de valores não preenchidos
    $inputs.each(function () {
        var $this = $(this);
        var val = $this.val();
        val || limpos++;
        $this.data("val-antigo", val);
    });

    $button.prop("disabled", !!limpos);

    // agora só vamos ouvir eventos específicos, e alterar a quantidade de limpos
    // quando um valor for alterado... não vamos mais iterar pelos controles
    $inputs.on("change keyup mouseup", function () {
        var $this = $(this);
        var val = $this.val();
        limpos += (val ? 0 : 1) - ($this.data("val-antigo") ? 0 : 1);
        $this.data("val-antigo", val);
        $button.prop("disabled", !!limpos);
    });
});

Example in jsfiddle

3

//funcao que permite a verificacao atravez de um seletor customizavel    
function isAnyEmpty(el){
    var isEmpty = false, v;
    el.each(function(e){
        v = $(this).val();
        if(v == "" || v == null || v == undefined){
            isEmpty = true
        }
    });
    return isEmpty;
}

Mode of use:

//use um seletor a sua escolha
var el = $('.meuformulario input[type="text"]');
el.on('keyup',function(){
    $('button').prop('disabled',isAnyEmpty(el));
});

This way you can reuse the function in any block of elements filtering with selectors, and can use together with other elements such as textarea for example.

VER FIDDLE

0

Alternative with pure Javascript

HTML form:

<form action="" id="form">
  <input type="text" placeholder="Digite seu nome">
  <input type="text" placeholder="Digite seu sobrenome">
  <button type="submit" disabled="disabled">Enviar</button>
</form>

You can add as many fields as you want, just put two to the example.

Now the required Javascript code:

function checkInputs(inputs) {

    var filled = true;
  
  inputs.forEach(function(input) {
    
    if(input.value === "") {
        filled = false;
    }
  
    });
  
  return filled;
  
}

var inputs = document.querySelectorAll("input");
var button = document.querySelector("button");

inputs.forEach(function(input) {
    
  input.addEventListener("keyup", function() {

    if(checkInputs(inputs)) {
      button.disabled = false;
    } else {
      button.disabled = true;
    }

  });

});

First we have the function checkInput, that will loop each of the inputs and verify that the value is filled

If any of them are, the variable filled is set to false, causing the return to be false and this determines that the form is not fully filled

Then we have an event in each of the inputs, which is activated with the keyup

In this event we will trigger the function to each key typed, to check if we release the form or not

And if the fields are filled in we will change the value of the disabled attribute to false

If the user removes data from some input again, we still check and if necessary we change the input to disabled again

Browser other questions tagged

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