JavaScript Coder

jQuery disable button on click to prevent multiple form submits

jquery disable button after click jquery disable button on submit

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.

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();
  });