Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable form button unless all text input fields are filled in

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?

like image 509
Paolo B Avatar asked Feb 11 '23 23:02

Paolo B


2 Answers

$('#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

like image 144
Sadikhasan Avatar answered Feb 13 '23 11:02

Sadikhasan


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;
}
like image 32
kontur Avatar answered Feb 13 '23 13:02

kontur