Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Philipp Munin Avatar asked Sep 12 '13 21:09

Philipp Munin


People also ask

What event triggers when a form is submitted?

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript. The method form. submit() allows to initiate form sending from JavaScript.

What is the event name that fires when a user submits a form?

The onsubmit attribute fires when a form is submitted.

What does Onsubmit event do?

The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server.


2 Answers

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

$("#MyForm").trigger('submit');
like image 108
Prisoner Avatar answered Oct 27 '22 19:10

Prisoner


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
like image 33
bfavaretto Avatar answered Oct 27 '22 18:10

bfavaretto