Mike Hogan Mike Hogan - 3 months ago 13x
jQuery Question

Simplest way to disable button on submission of a form?

I've been trying to find the "right" way to prevent double submits of forms. There are lots of related posts on SO but none of them hit the spot for me. Two questions below.

Here is my form

<form method="POST">
<input type="text" name="q"/>
<button class="once-only">Send</button>

Here is my first attempt to disable double submits:

this.disabled = true;
return true;

This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference. You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/

As you can see, this disables the button, but also prevents submission of the form. In cases where the submitting element is a button and an input element.

Question 1: why does this click handler stop submission of the form?

Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)

if($.data(this, 'clicked')){
return false;
} else{
$.data(this, 'clicked', true);
return true;

You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/

This does work, but...

Question 2: Is this the best we can do?

I thought this would be an elementary thing. Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.


You can use jQuery's submit(). In this case, it should look something like this:

    $(this).children('input[type=submit]').prop('disabled', true);

Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.

If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:

    $(this).find('button[type=submit]').prop('disabled', true);

Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/