Chris Chris - 5 months ago 8
jQuery Question

How do I delay a form from submitting

I have an additional function to execute before I submit the form. This isn't doing the trick.

$('form').submit( function(event) {
var formId = $(this).attr('id');
mySpecialFunction(formId);

event.preventDefault();

setTimeout( function () {
$(this).submit();
}, 300);

});


This isn't working obviously.

Answer

You need to fire the event on the form element itself, not on a jQuery selection. (In fact, you weren't even selecting the form element – inside setTimeout, this is the global object.)

Cache a reference to the form (this) and call its submit method:

$('form').submit( function(event) {
    var formId = this.id,
        form = this;
    mySpecialFunction(formId);

    event.preventDefault();

    setTimeout( function () { 
        form.submit();
    }, 300);
}); 

Note that I have also replaced your inefficient $(this).attr('id') call with this.id. Note also that you have to call the DOM form element's submit method, not the jQuery method, so that the jQuery event handler is not triggered, which would cause an infinite (and totally ineffectual) loop.