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();
2 Answers 2
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.
-
\$\begingroup\$ The this reference goes a bit strange in setTimeout. \$\endgroup\$Bradley Moore– Bradley Moore2012年01月13日 14:53:31 +00:00Commented Jan 13, 2012 at 14:53
-
\$\begingroup\$ I edited to alias
this
asthat
, see if that works for you. \$\endgroup\$Adam Tuttle– Adam Tuttle2012年01月13日 14:56:24 +00:00Commented Jan 13, 2012 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
.