Reputation: 15955
I have a form that I would like to submit via JavaScript. Obviously this can be achieved by:
document.getElementById("myForm").submit();
The issue is that I have a listener on the submit
event that looks like this:
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
// Other work
});
This event handler is not triggered when I call .submit()
. From MDN:
The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.
So, given this restraint, how can I submit the form in a way that ensures the event handler is invoked?
Upvotes: 36
Views: 36627
Reputation: 2224
Update Nov 21, 2022
I would now recommend the requestSubmit()
method. You can pass a submit button to it if you want. Its cleaner and can be intercepted.
document.getElementById("myForm").requestSubmit();
Original answer
A custom event works just fine.
document.getElementById("myForm").dispatchEvent(new CustomEvent('submit', {cancelable: true}));
Upvotes: 28
Reputation: 2495
You need create a submit event, then dispatch it.
(function () {
if ( typeof window.CustomEvent === "function" ) return false;
function CustomEvent ( event, params ) {
params = params || { bubbles: true, cancelable: true, detail: undefined };
var evt = document.createEvent('submit');
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var evt = new CustomEvent("submit", {"bubbles":true, "cancelable": true});
document.getElementById("myForm").addEventListener("submit",function(event) {
event.preventDefault();
alert('submit');
});
Then when you want submit this function you need to call:
!document.getElementById("myForm").dispatchEvent(evt);
For more event info see dispatchEvent.
Upvotes: 14
Reputation: 3418
Use jQuery to submit the form and add the handler.
$("#myForm").on("submit", function(e){
e.preventDefault();
// Handle submission here
});
// Then later
$("#myForm").submit();
Upvotes: -11