Search code examples
javascriptjqueryformsdisabled-input

How do I use jQuery to disable a form's submit button until every required field has been filled?


I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.

How can I accomplish this with jQuery?


Solution

  • Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:

    $('#submitBtn').prop('disabled', true);
    $('.requiredInput').change(function() {
       inspectAllInputFields();
    });
    

    We then would have a function that checks every input and if they're validated then enable the submit button...

    function inspectAllInputFields(){
         var count = 0;
         $('.requiredInput').each(function(i){
           if( $(this).val() === '') {
               //show a warning?
               count++;
            }
            if(count == 0){
              $('#submitBtn').prop('disabled', false);
            }else {
              $('#submitBtn').prop('disabled', true);
            }
    
        });
    }
    

    You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.

     inspectAllInputFields();
    

    Hope this helps, ~Matt