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.
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.
The onsubmit attribute fires when a form is submitted.
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.
That's because you shouldn't just use the submit
function, but trigger
the submit like:
$("#MyForm").trigger('submit');
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With