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();
asked Jan 13, 2012 at 14:35
\$\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.

answered Jan 13, 2012 at 14:49
\$\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.

answered Jan 13, 2012 at 15:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.