jjanes jjanes - 4 months ago 28
jQuery Question

Prevent double form submission

I am trying to adapt a bunch of existing web apps to prevent users from accidentally bouncing on the submit button and submitting the form twice. I thought jquery would be the best way to do this, although my pages use very little jquery otherwise.

I've found many similar questions here, and the answers have been very useful but still do not offer a complete and simple solution. The first solution I hit upon was this:

$(document).ready(function(){
$('form').submit(function(){
$("input[type=submit]").prop("disabled", true);
});
});


It works very well, greying out the submit button(s) after the form is submitted. The problem is that the value of the submit button itself does not get submitted with the form, I guess because it is disabled. Usually that is not a problem, but for some of the applications it is because they depend on the value of the submit button for correct operation. I would like something more general that will work for those pages without having to redesign them.

I then tried this other example:

$(document).ready(function(){
$('form').submit(function(){
$(this).submit(function() {
return false;
});
return true;
});
});


This works well for disabling multiple submissions while still transmitting the value of the submit button, but it does not grey out the submit button, so there is no visual indication that the submission has occured. I will probably go with if I cannot find a better solution, but I would like both to transmit the value for the button, and to grey out the button.

I finally tried this:

$(document).ready(function(){
$('form').submit(function(){
this.submit();
$("input[type=submit]").prop("disabled", true);
return false;
});
});


However, it seems to be like the first example in that the submit button value is not transmitted with the form, despite that the this.submit() apparently should be happening before the disabling.

I've also tried just hiding the button, but that causes the page to get re-arranged, and the poor user will accidentally hit something completely different on the mouse bounce, rather than hitting the submit twice.

I could replace the button with something of the same size, or try to copy the submit value into a hidden input element with the name, but that is getting grotesque. Is there a simple way to meet this simple need?

Answer

Instead of binding the submit event of FORM, try using the click handler of submit button and used:

$('form :submit').click( function () {
    $(this).prop("disabled", true).closest('form').append($('<input/>', {
        type: 'hidden',
        name: this.name,
        value: this.value
    })).submit();
});