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?
dispatchEventalongside your.submit()calldispatchEvent? According to MDN,dispatchEventis supported across browsers, but callingnew Event()is not. How else can an event be constructed?var evt = document.createEvent("Event"); evt.initEvent("submit", true, true); form.dispatchEvent(evt);link