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?
In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.
You can tie a submit button to a form that the button doesn't live inside of. The trick is to give the form an id and then reference that id with the button's form property. With this setup, clicking the Submit button will cause the form to be submitted.
The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.
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.
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