Disable form button unless all text input fields a

2019-06-26 00:33发布

问题:

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.

I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.

    <script>
        $(function () {
            $('#button').attr('disabled', true);

            $('input:text').keyup(function () {
                $('#button').prop('disabled', this.value == "" ? true : false);
            })
        });
    </script>

I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?

回答1:

$('#button').attr('disabled', true);
$('input:text').keyup(function () {
   var disable = false;
       $('input:text').each(function(){
            if($(this).val()==""){
                 disable = true;      
            }
       });
  $('#button').prop('disabled', disable);
});

Demo



回答2:

The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.

$('input:text').keyup(function () {
    $('#button').prop('disabled', allFieldsAreFilled());
});

function allFieldsAreFilled() {
    var allFilled = true;
    // check all input text fields
    $("#yourForm input:text"]).each(function () {
        // if one of them is emptyish allFilled is no longer true
        if ($(this).val() == "") {
            allFilled = false;
        }
    });
    return allFilled;
}


回答3:

Try this:

$(function() {
  var bool = true, flag = false;
  $('#button').prop('disabled', bool); // use prop to disable the button

  $(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
    $('input:text').each(function() { // loop through each text inputs
      bool = $.trim(this.value) === "" ?  true :  false; // update the var bool with boolean values
      if(bool)
      return flag;
    });
    $('#button').prop('disabled', bool); // and apply the boolean here to enable
  });
});
<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' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />