4
\$\begingroup\$

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();
\$\endgroup\$
0

2 Answers 2

3
\$\begingroup\$

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;
        jQuery(this).addClass("locked");
        that = this;
        setTimeout(function() {
            jQuery(that).removeClass("locked");
        }
        , duration );
    });
};

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

\$\endgroup\$
2
  • \$\begingroup\$ The this reference goes a bit strange in setTimeout. \$\endgroup\$ Commented Jan 13, 2012 at 14:53
  • \$\begingroup\$ I edited to alias this as that, see if that works for you. \$\endgroup\$ Commented Jan 13, 2012 at 14:56
2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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