HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Prevent Double Form Submit within X seconds

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
preventsecondswithindoublesubmitform

Problem

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();

Solution

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.

Code Snippets

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 );
    });
};

Context

StackExchange Code Review Q#7769, answer score: 3

Revisions (0)

No revisions yet.