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
2 Answers
Reset to default 16When 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
版权声明:本文标题:javascript - Why does a `submit` event listener not work on a submit button? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738738845a2109728.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论