2

I want to disable a form submit button after it's clicked to prevent the form being submitted multiple times. I use the following code to disable the button and add a class that makes it appear disabled:

$("form button.primaryAction").click(function() {
    $(this).prop("disabled", true).addClass('disabledBtn');
    return true;
});

It works fine in IE and Firefox, but in Chrome 17 the form doesn't get submitted. I guess I could replace the code above with:

$("form button.primaryAction").click(function() {
    $(this).prop("disabled", true).addClass('disabledBtn');

    var form = // how can I get a reference to the form from the button 'this' ?
    form.submit();
    return false;
});

But as you can see I'm not sure how to get a reference to the form from inside the click handler.

Dónal
  • 185,044
  • 174
  • 569
  • 824

3 Answers3

3

this.form will give you the reference.

All form-elements (buttons, inputs, select's etc.) have a property form which points to the form-element they belong to.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • 1
    +1 though I'm still curious to know why the original code doesn't work in Chrome? – Dónal Feb 19 '12 at 17:23
  • I guess it's because you disabled the button before the form gets submitted, looks like this prevents the click from propagation. Instead of using submit() it also should be possible to use a short delay before disabling the button.(in some case this may be important, e.g. when you need information about the clicked button on serverside) – Dr.Molle Feb 19 '12 at 18:29
2

You might be able to bypass this issue by using jquery's submit() function rather than the click() function. The contained function will only fire after the submit action takes place.

Nick G.
  • 1,145
  • 2
  • 10
  • 19
1

Your code doesn't make sense! First you disable the default submit and then submit manually.

$("form button.primaryAction").click(function() {
    $(this).prop("disabled", true).addClass('disabledBtn');

    var form = this.form;
    form.submit(); // submits the form
    return false;  // disable the defualt submit.... ?!
});

Don't cancel the automatic submit and that's it!

$("form button.primaryAction").click(function() {
    $(this).prop("disabled", true).addClass('disabledBtn');
});

I would write it this way:

$("form").submit(function() {
    $('button.primaryAction').prop("disabled", true).addClass('disabledBtn');
});
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • your suggestion is how the code originally looked, i.e. with not return statement. The form wasn't submitting in Chrome with that code – Dónal Feb 19 '12 at 19:17
  • @Don. maybe you have another submit handler that return false thus prevent the submit? – gdoron Feb 19 '12 at 19:29