submit event does not fire if submit initiated programmatically

I have a HTML form with button:

<form action="/" method="post" id="MyForm">
<input type="hidden" name="Field1" value="Value1" />
<input type="hidden" name="Field2" value="Value2" />
<input type="submit" name="name" value="submit" />
</form>

I have event handler for submit attached to Window:

window.onsubmit = function()
{
    alert("Submit happening!");
};

This event handler fires properly if I click "Submit" button. However events never works when submit is triggered programmatically from javascript:

$("#MyForm")[0].submit();

How to catch submit event handler when it was initiated by Javascript, not by User click? I tried to subscribe for Form event using Jquery or AddEventListener - does not work.


Solution 1:

That's because you shouldn't just use the submit function, but trigger the submit like:

$("#MyForm").trigger('submit');

Solution 2:

Browsers don't fire the form's onsubmit handler when you manually call form.submit().

jQuery also mimicks used to mimick that (see this "wontfix" "bug" report).

See also:

  • Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?
  • JQuery: on submit doesn't work