Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onsubmit method vs submit event listener

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('#compose-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('#compose-form').onsubmit = () => {

send_email();

load_mailbox('inbox');

return false;

}
like image 568
AAM Avatar asked Oct 22 '25 04:10

AAM


1 Answers

The difference is that onsubmit replaces the current (already assigned) function. addEventListener on the other hand adds an additional command 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('#compose-form').addEventListener('submit', (event) => {
  event.preventDefault(); // add this line

  // and then do your stuff
  send_email();
  load_mailbox('inbox');
  return false;

})
like image 129
Adam Orłowski Avatar answered Oct 24 '25 16:10

Adam Orłowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!