I want to prevent double form submissions within a small window, then allow the form to be submitted again.

I wrote this script after looking at several examples, but the global variable is bugging me. I'd welcome any suggestions on improving it.

var aLockedForms=   [];
jQuery.fn.preventDoubleSubmit=  function() {

    jQuery( this ).submit( function() {
        if ( this.beenSubmitted )
            return false;

        this.beenSubmitted= true;

        aLockedForms.push( this );

        setTimeout( function() {
                        var domTarget=  aLockedForms.shift();
                            domTarget.beenSubmitted=    false;

                    } ,
                    1984 );



After the DOM is loaded, I run the following:

$( "form" ).preventDoubleSubmit();

Regarding the global variable, you're already using jQuery so why not just attach an attribute or class to the form?

jQuery.fn.preventDoubleSubmit=function(duration) {
    duration = duration || 1984;
    jQuery( this ).submit( function() {
        if ( this.hasClass("locked") ) return false;
        that = this;
        setTimeout(function() {
        , duration );

You may want to change the class name to something a little more unique, but that should work.

  • \$\begingroup\$ The this reference goes a bit strange in setTimeout. \$\endgroup\$ – Bradley Moore Jan 13 '12 at 14:53
  • \$\begingroup\$ I edited to alias this as that, see if that works for you. \$\endgroup\$ – Adam Tuttle Jan 13 '12 at 14:56

You could wrap the entire thing in an anonymous function that you immediately execute:

(function() {
  var aLockedForms = [];


Edit: I want to clarify that this is something you can do to eliminate global variables in the future. Adam Tuttle's answer is better in this case because it eliminates the variable entirely by properly utilizing the closure inside setTimeout.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.