I have a submit event handler on a form (to catch people submitting the form with enter, which sometimes I need to fire manually (triggered by the user clicking on something other than a submit button), via dispatchEvent.
I don't want it to actually submit the form though, but once dispatchEvent has been fired it seems I can't cancel it?
myForm.addEventListener('submit', function(e) {
e.preventDefault();
console.log(e.defaultPrevented); // false
});
myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail'}));
In Chrome this still outputs false
, but the form doesn't submit (the desired behaviour). In fact even if I remove the preventDefault() line it still doesn't submit?
However, Firefox is a different story, and always submits the form.
How can I change this?
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
preventDefault() prevents the default behaviour, it is not related to bubbling or not the events, so you can safely ignore it. Follow this answer to receive notifications.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
You have to explicitly code your event with the cancelable property to be TRUE and by default, this is not handled.
myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail', cancelable: true}))
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