admin管理员组

文章数量:1208153

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 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>

Share Improve this question edited Oct 31, 2022 at 17:32 Sebastian Simon 19.5k8 gold badges60 silver badges84 bronze badges asked Sep 17, 2015 at 18:51 user5096599user5096599 2
  • already answered, here is the link: stackoverflow.com/questions/7194673/… – Lucas Commented Sep 17, 2015 at 18:54
  • Does this answer your question? preventDefault() submitting form – Brian Tompsett - 汤莱恩 Commented Nov 23, 2020 at 14:39
Add a comment  | 

2 Answers 2

Reset to default 16

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.

本文标签: javascriptWhy does a submit event listener not work on a submit buttonStack Overflow