javascriptsubmitaddeventlistenerevent-listener

Why does the second eventlistener not fire?


I have two event listeners on my page, but the second one does not fire when I click the button. How do I get the submit event listener to fire?

document.getElementById("myButton").addEventListener("click", function(e) {
  e.preventDefault();
  document.getElementById("myForm").submit();
});
document.getElementById("myForm").addEventListener("submit", function(e) {
  e.preventDefault();
  console.log("submit triggered")
});
<form id="myForm">
  <input><br>
  <button id="myButton" type="button">Click</button>
</form>


Solution

  • According to this link, 'submit' event fires when user submits a form not when you submit a form using script.

    Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.