Home > Software design >  Does 'submit()' method impede 'submit' event listener to be executed?
Does 'submit()' method impede 'submit' event listener to be executed?

Time:04-22

I feel like I'm asking "what's 2 2 ?" but I'm facing an issue I don't understand... Here is the code, easy to understand:

<button type="button" onclick="send()">
<form id="form">
  <input name="name">
</form>

<script>
  const form = document.getElementById("form");
  function send() {
    form.submit();
  }
  form.addEventListener("submit", (e)=>{
    // This code never gets executed,
    // the default behavior still works.
    // (note that my console preserves logs,
    // so it should be visible even though the page is being refreshed.)
    console.log("preventing default behavior");
    e.preventDefault();
  });
</script>

Could someone help me on that one ? It should be so easy but for some reason the code doesn't want to be nice with me tonight.

CodePudding user response:

This is the (somewhat unintuitive) expected behavior. See the docs for HTMLFormElement.submit():

This method is similar, but not identical to, activating a form's submit . When invoking this method directly, however:

  • No submit event is raised. In particular, the form's onsubmit event handler is not run.

  • Constraint validation is not triggered.

The HTMLFormElement.requestSubmit() method is identical to activating a form's submit and does not have these differences.

So, you can use form.requestSubmit instead of form.submit.

CodePudding user response:

  const form = document.getElementById("form");
  function send() {
    form.submit();
  }
  form.addEventListener("submit", (e)=>{
    // This code never gets executed,
    // the default behavior still works.
    // (note that my console preserves logs,
    // so it should be visible even though the page is being refreshed.)
    
    e.preventDefault();
    console.log("preventing default behavior");
    send();
  });
<form id="form">
  <input name="name">
  <button type="submit" >submit</button>
</form>

  • Related