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
Add a ment  | 

1 Answer 1

Reset to default 7

The 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