How can I prevent a double submit with jQuery or Javascript?

This should do the trick:

$("form").submit(function() {
   $(":submit", this).attr("disabled", "disabled");
});

No JQuery?

Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.


One technique I've seen used is to assign a unique ID to every form that's opened, and only accept one submission per form based on the ID.

It also means you can check how many times people aren't bothering to submit at all, and you can check if the submission genuinely came from your form by checking if it's got an ID that your server created.

I know you asked for a javascript solution, but personally I'd do both if I needed the robustness.


How about disabling the button on submit? That's what I do. It works fine.

$('form').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.

I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.


Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:

  • button elements
  • img elements
  • javascripts
  • pressing 'enter' while on some text field

Using jQuery data container would be my choice. Here's an example:

$('#someForm').submit(function(){
    $this = $(this);

    /** prevent double posting */
    if ($this.data().isSubmitted) {
        return false;
    }

    /** do some processing */

    /** mark the form as processed, so we will not process it again */
    $this.data().isSubmitted = true;

    return true;
});