Codemonkey Codemonkey - 1 year ago 129
Javascript Question

How can I preventDefault() on dispatchEvent?

I have a submit event handler on a form (to catch people submitting the form with , 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) {
console.log(e.defaultPrevented); // false

myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail'}));

In Chrome this still outputs
, 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?

Answer Source

By default created event is not. You have to make your event cancelable.

 myForm.dispatchEvent(new Event('submit', {'detail': 'mydetail', cancelable: true}))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download