Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.


This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.


I suppose it's reasonable to want this behavior in some cases, but I would argue that code not triggering a form submission should (always) be the default behavior. Suppose you want to catch a form's submission with

$("form").submit(function(e){
    e.preventDefault();
});

and then do some validation on the input. If code could trigger submit handlers, you could never include

$("form").submit()

inside this handler because it would result in an infinite loop (the SAME handler would be called, prevent the submission, validate, and resubmit). You need to be able to manually submit a form inside a submit handler without triggering the same handler.

I realize this doesn't ANSWER the question directly, but there are lots of other answers on this page about how this functionality can be hacked, and I felt that this needed to be pointed out (and it's too long for a comment).