addEventListener using submit is not working
Solution 1
When I use the 'click' event, my code works and it prevents the form from submitting. However, when I use this code it does not. Why?
The submit
event is only triggered on the <form>
element.
Since you say it works for click
, I assume you are not binding the handler to the <form>
element.
From the MDN documentation:
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or submit input. (Forms are submitted, not buttons.)
Solution 2
If submitMessage
is the form then make sure that the submit button has the type
attribute set as submit
in the html file. In my case, the type of the submit button was button
and it gave me headaches because I thought the problem was in the js file. It looks like a small problem but it can get you pretty stuck.
Mike
Updated on August 04, 2022Comments
-
Mike over 1 year
When I use the 'click' event, my code works and it prevents the form from submitting. However, when I use this code it does not. Why?
submitMessage.addEventListener('submit', sendMessage, false); function sendMessage(event){ event.preventDefault(); console.log('made it'); }