admin管理员组文章数量:1429769
I have been doing a mail program for a course, and I am encountering behaviour I do not understand related to preventing form submission via return false:
Case 1: Form submission is not properly prevented and DOM is reloaded giving a 200 error
document.querySelector('#pose-form').addEventListener('submit', () => {
send_email();
load_mailbox('inbox');
return false;
})
Case 2: Form submission is properly prevented and DOM is not reloaded returning an expected 201 code
document.querySelector('#pose-form').onsubmit = () => {
send_email();
load_mailbox('inbox');
return false;
}
I have been doing a mail program for a course, and I am encountering behaviour I do not understand related to preventing form submission via return false:
Case 1: Form submission is not properly prevented and DOM is reloaded giving a 200 error
document.querySelector('#pose-form').addEventListener('submit', () => {
send_email();
load_mailbox('inbox');
return false;
})
Case 2: Form submission is properly prevented and DOM is not reloaded returning an expected 201 code
document.querySelector('#pose-form').onsubmit = () => {
send_email();
load_mailbox('inbox');
return false;
}
Share
Improve this question
asked Mar 13, 2021 at 9:46
AAMAAM
971 silver badge5 bronze badges
1
-
1
Use
event.preventDefault
when using addEventListener – Keith Commented Mar 13, 2021 at 9:54
1 Answer
Reset to default 7The difference is that onsubmit
replaces the current (already assigned) function. addEventListener
on the other hand adds an additional mand to the already existent property.
So in your case when using addEventListener
you need to prevent the default behavior with a preventDefault
function.
Try this:
// add event as an argument
document.querySelector('#pose-form').addEventListener('submit', (event) => {
event.preventDefault(); // add this line
// and then do your stuff
send_email();
load_mailbox('inbox');
return false;
})
本文标签: javascriptonsubmit method vs submit event listenerStack Overflow
版权声明:本文标题:javascript - onsubmit method vs submit event listener - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745551162a2662949.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论