Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener using submit is not working

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>
like image 957
Mike Avatar asked Sep 17 '15 18:09

Mike


2 Answers

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

like image 93
Felix Kling Avatar answered Nov 03 '22 00:11

Felix Kling


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.

like image 2
DanGeros Avatar answered Nov 03 '22 02:11

DanGeros