When I use the click
event, my code works and it prevents the form from submitting. However, when I use the submit
event, it does not. Why?
const submitMessage = document.getElementById("submitButton");
submitMessage.addEventListener("submit", sendMessage, false);
function sendMessage(event) {
event.preventDefault();
console.log("Made it");
}
<form>
<input id="submitButton" type="submit">
</form>
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.)
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.
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