1

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?

Reporter
  • 3,897
  • 5
  • 33
  • 47
jkupczak
  • 2,891
  • 8
  • 33
  • 55
  • Are you using RequiredFieldValidators or are you using jQuery validators? – James Johnson Oct 13 '11 at 14:51
  • 1
    Can you show us some of the html / JavaScript you already have? – Mark Oct 13 '11 at 14:52
  • *related* [How to disable submit button in jQuery if form fields have not been modified?](http://stackoverflow.com/questions/881144/how-to-disable-submit-button-in-jquery-if-form-fields-have-not-been-modified) – Felix Kling Oct 13 '11 at 14:53
  • try using each to pass in all fields , if all have length or value , show enable the button – Ricardo Binns Oct 13 '11 at 14:53
  • @JamesJohnson - I'm using the `required` HTML5 Form attribute on my inputs. For validation I'm using classic ASP once they submit the form. @Mark I can show you this page right now: http://iavi.com/menu/itemdesc.asp?ic=PLCXR251 My form is located at the top of the page when you click the "Get A Quote" image. @ric_bfa That's what I figured, but as a novice in jQuery I need a more complete write up. – jkupczak Oct 13 '11 at 15:26

6 Answers6

8

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

sirmdawg
  • 2,579
  • 3
  • 21
  • 32
  • as with jquery 1.6.+, it is better to access the native "disabled" property, rather than through it's attribute. ie use `$(input:submit).prop('disabled', true/false);` instead of `.attr('disabled', 'enabled/disabled')` – roselan Oct 13 '11 at 15:00
  • Testing `!$(this).val()` will fail for values like "0", even if that's a legitimate input to enter. – Blazemonger Oct 13 '11 at 15:03
  • Just threw the answer together but you're right. So adding == "" would fix this correct? – sirmdawg Oct 13 '11 at 15:05
  • You need to test `val === ''`, with three equals. https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators – Blazemonger Oct 13 '11 at 15:23
  • Thanks for the reply! I tried this on my site and couldn't get it to work. So I replicated your code on jsfiddle. Still no luck. I have to imagine that with all or even 1 field empty, the submit button should have no action when clicked, right? This isn't the case on the test page. Could you tell me what I did wrong? http://jsfiddle.net/P8BqU/ – jkupczak Oct 13 '11 at 15:59
  • Fixed it, like I said, I didn't actually test it or anything :P But it should work now. – sirmdawg Oct 13 '11 at 16:10
  • There it is! All fixed. Thanks! – jkupczak Oct 13 '11 at 16:12
  • Encountered an instance where this does not work. If the required field is already entered on page load, the submit button remains disabled until that field is cleared of its value, and then a value is re-entered. Any idea how to work around this? – jkupczak Oct 13 '11 at 16:34
  • try running inspectAllInputFields(); when the page first loads ;) – sirmdawg Oct 13 '11 at 16:42
  • I added this and it seemed to do the trick. `$(document).ready( function() { inspectAllInputFields(); });` Is this the best way to handle it? – jkupczak Oct 13 '11 at 16:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4238/discussion-between-mkprogramming-and-jimmykup) – sirmdawg Oct 13 '11 at 16:44
4

Here's something comprehensive, just because:

$(document).ready(function() {
    $form = $('#formid'); // cache
    $form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
    $form.find(':input').change(function() { // monitor all inputs for changes
        var disable = false;
        $form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
            if ($.trim(el.value) === '') {
                disable = true; // disable submit if any of them are still blank
            }
        });
        $form.find(':input[type="submit"]').prop('disabled', disable);
    });
});

http://jsfiddle.net/mblase75/xtPhk/1/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • This answer also worked for me. I found the other answer easier to read and understand for me though. Thank you for your help! – jkupczak Oct 13 '11 at 16:13
0

Set the disabled attribute on the submit button. Like:

$('input:submit').attr('disabled', 'disabled');

And use the .change() event on your form fields.

Sanjo
  • 1,240
  • 9
  • 11
0

Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.

There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.

You can get around the second by either

  • disabling the button with onkeydown and checking if it is ok on onkeyup
  • checking for validity when the button is clicked
yoozer8
  • 7,361
  • 7
  • 58
  • 93
0

An idea from me:

  • Define a variable -with global scope- and add the value true- Write a submit function within your check the value above varibale. Evalue the the submit event only, if the value is true.
  • Write a function which ckecks all value from input fields and select fields. Checking the length of value to zero. if the value length of one field zero then change the value of the global variable to false.
  • After that, add to all input fields the event 'onKeydown' or 'onKeyUp' and to all select boxes the event 'onChange'.
Reporter
  • 3,897
  • 5
  • 33
  • 47
0

I recommend taking a slightly different approach and using jquery's validation http://docs.jquery.com/Plugins/validation. The tactic you are suggesting is prone to security holes. The user could easily using firebug enable that button and then submit the form.

Using jquery validation is clean and it allows you to show error messages under the required fields if so desired on submit.

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
  • I'm using asp on the backend to validate the fields. I just don't want them to submit the form if they haven't even finished filling it out. Not worried about someone firebugging the page to get around it, because the asp will just stop the form from submitting altogether. – jkupczak Oct 13 '11 at 16:10
  • imho, you should always strive to do client AND serverside validation. For two reasons. One, it is a double check and two. It reduces a serverside call which takes up bandwidth. – Keith.Abramo Oct 13 '11 at 16:12