views:

70

answers:

2

I'd like to disable a form after it is submitted in order to prevent double submissions. Pretty standard use case I would think, but all of the examples I can find out there are flawed.

Everything I can find is based on disabling the submit button, but this doesn't prevent the form from being re-submitted if the user hits the enter key on the form, which is a pretty common approach.

I'm thinking about modifying one of the existing scripts out there to account for this, but before I reinvent the wheel, does anyone know of a script that already handles this properly that they're able to share? I'm really surprised there doesn't seem to be anything out there yet.

+4  A: 

You could create a boolean variable (or an object with a boolean member variable) and only submit the form when the variable is false. Something like:

function init() {
    var submit = false;
    var f = document.getElementById("FormID");
    f.onsubmit = function() {
        if(submit) {
            return false;
        } else {
            submit = true;
            return true;
        }
    }
}

Of course, you would have to call init following the page load, in whichever flavor you choose to do that (window.onload = ..., window.addEventListener(...), window.attachEvent(...), etc.).

palswim
I'm having some trouble with your solution. Conceptually it makes clear sense, but when I implemented it, in practice I seem to be able to sneak in an extra click if I repeatedly slam the submit button as fast as I can. It's almost as if a second onsubmit is being initiated before the first has had time to set submit to true. However, when I stick in alerts, everything seems to be working as I would expect.
WIlliam Jones
Oddly enough, the double submit script works perfectly against the enter key. It's only using the mouse to click the submit button that double posts still slip through.
WIlliam Jones
Hmm, last piece of info, this repeated submit with mouse problem doesn't happen in latest Chrome or IE, only latest Firefox. Maybe I'm prepared to just accept this then as an obscure Firefox bug and write them off.
WIlliam Jones
@williamjones: Weird; I'll let you know if I find anything about that.
palswim
+2  A: 

http://jsfiddle.net/c2N4v/

var sent = false;
$('#form').submit(function(e) {
    if (!sent) {
        sent = true;
        // do whatever
    }
    else e.preventDefault();
});
Robert