Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delay a form from submitting

Tags:

jquery

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.

like image 353
Chris Avatar asked Jan 11 '12 23:01

Chris


People also ask

How do you stop something from submitting?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do you stop a form from being submitted twice?

Returning "false" from the submit handler will prevent the form from submitting.

How do you delay a submission in JavaScript?

Here is the way that works for me: const form = $("#formId"); form. submit(() => { //some other functions you need to proceed before submit setTimeout(() => {}, 1200); return true; }); Now it will wait 1200 ms before submitting the form.


2 Answers

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.

like image 163
lonesomeday Avatar answered Oct 11 '22 10:10

lonesomeday


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

    mySpecialFunction(formId);

    event.preventDefault();
    $this.unbind("submit");
    setTimeout( $.proxy( $.fn.submit, $this ), 300);

}); 
like image 23
Esailija Avatar answered Oct 11 '22 10:10

Esailija