jviotti
jviotti

Reputation: 18929

Code inside submit event executes after or before form submitting?

Does the code inside $('form').submit(function() {}); executes before or after the form submit?

For example, if I edit the value of one of the inputs there, will the new value be included on the request?

Upvotes: 0

Views: 104

Answers (1)

Corbin
Corbin

Reputation: 33447

It executes before the form submits. Otherwise the page would have changed, and since the JavaScript environment is associated with the page, it would have changed too. That would leave you executing in a potentially rather odd context.

$("form").submit(function(){
    $(this).append('<input type="hidden" name="foo" value="bar" />');
});

Will mean that every form will have that input appended before submitting (assuming JS is enabled).

Similarly:

$("#someForm").submit(function() {
    if (/* something */) {
        alert("Form invalid"); //alert() is terrible, but you get the point
        return false; //Blocks submission
    } else {
        return true;
    }
});

(Note: depending on the situation and other bindings, using preventDefault would likely make more sense -- I'm just lazy.)

Upvotes: 1

Related Questions