Jquery disable button on click to prevent multiple form submits

The default behavior of a submit button obvious – clicking it submits the contents of a form to the server. This seems quite straightforward. So, what could possibly go wrong?

Well, what if the user double clicks on the submit button rather than clicking it just the once? The contents of the form will be submitted twice.

If there is no response to indicate the form was submitted, some users will click again and the form will get submitted again.

The solution is simple: disable the button or hide the button once the form is submitted. Also show a status (like ‘Submitting …’)

Disable all submit buttons while the form is submitting

Here is the jQuery Code:

$('#theform').submit(function()
{
$("input[type='submit']", this)
.val("Please Wait...")
.attr('disabled', 'disabled');
return true;
});

‘theform’ is the id of the form.
The code above captures the submit event. Note the this in the code $("input[type='submit']", this). That means, disable the submit buttons in the current form only. There can be several forms in the same page. We don’t want to disable all of them.

$(function()
{
$('#theform').submit(function(){
$("input[type='submit']", this)
.val("Please Wait...")
.attr('disabled', 'disabled');
return true;
});
});

When you are using a simple button to submit

When you are having a <input type=’button’ …/> rather that submit button, you can use the code below:

<input  type="button" value="Submit" id='btnsubmit' />   
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});

Be Sociable, Share!

Comments on this entry are closed.

  • Syed Anuar

    if user type an error input and system will go back.. problem. button already disabled by firefox..

  • Goujon

    Works like a charm, but in my case it’s user defined button, so ‘input’ doesn’t work. Changed input and .val to button and .text to make it work properly. But I have another question: how to add other forms (I have 3 modal forms on the same page) to this script? Or should I copy/paste it for all three forms ids?

  • Dhiraj Dhakal

    Hi, sometime on clicking the button multiple times very quickly, the disable function does not work and it can still be clickable. Can you let me know why is that ? is it a bug in jquery itself?