Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Stop submitting form, perform script, continue submitting form?

Tags:

I have a form, and when I submit him I execute multiple script. Here is my code:

$("#RequestCreateForm").submit(function (e) {
    if ($("#RequestCreateForm").validate().checkForm() == false) { return; }

    e.preventDefault();

    //many scripts

    //How to continue submitting?
}

Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?

Thank you

like image 741
Tuizi Avatar asked May 24 '11 16:05

Tuizi


People also ask

How do I stop a form from submitting in JQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

How do I stop form submitting multiple times?

Use JQuery to Prevent Multiple Form Submissions To prevent the user from submitting a form multiple times, we'll use JQuery to listen for the submission event. Once the form is submitted, we'll add a disabled attribute to the button to prevent multiple form submissions. Now the user can't click it again.

How do I stop a form from submitting?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.

How Stop JavaScript submit?

One way to stop form submission is to return false from your JavaScript function.


2 Answers

When you call $("#RequestCreateForm").submit(), the script will just run through the event handler again, and cause an infinite loop (as Koen pointed out in a comment on the accepted answer). So, you need to remove the event handler before submitting:

$("#RequestCreateForm").on('submit', function (e) {
    e.preventDefault();
    // do some stuff, and if it's okay:
    $(this).off('submit').submit();
});

The last line needs to be in a conditional statement, otherwise it'll just always happen, and negate your e.preventDefault(); at the top.

like image 190
Chris Avatar answered Oct 05 '22 20:10

Chris



$("#RequestCreateForm").submit(function (e) {
    if ($("#RequestCreateForm").validate().checkForm() === false) { 
       e.preventDefault(); 
       //form was NOT ok - optionally add some error script in here

       return false; //for old browsers 
    } else{
       //form was OK - you can add some pre-send script in here
    }

    //$(this).submit(); 
    //you don't have to submit manually if you didn't prevent the default event before
}
like image 27
Adrian J. Moreno Avatar answered Oct 05 '22 18:10

Adrian J. Moreno