Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preventDefault() on dispatchEvent?

Tags:

javascript

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?

like image 607
Codemonkey Avatar asked Dec 01 '16 17:12

Codemonkey


People also ask

How do you use event preventDefault?

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.

What does preventDefault () do?

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.

What is event preventDefault () in angular?

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.

What is e preventDefault () in jquery?

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.


1 Answers

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}))
like image 74
sandyJoshi Avatar answered Oct 15 '22 21:10

sandyJoshi