Search code examples
javascript

Why submit() method didn't trigger onsubmit event?


I have a form like below:

<form action="/action_page.php" onsubmit="alert('The form was submitted');" >
  Enter name: <input type="text" name="fname">
  <input type="button" onclick="document.getElementsByTagName('form')[0].submit()" value="Submit">
</form>

Though I clicked the button and indeed it submitted the form, but the alert box wasn't shown. That is, the submit() method submitted the form but without triggering the onsubmit event. What happened? And how should I use submit() method to trigger the onsubmit event?


Solution

  • Well, the documentation for the submit method is pretty clear that it doesn't trigger onsubmit.

    Since any of the following form elements cause a form submit:

    <input type="submit">
    <button>
    <button type="submit">
    

    You likely don't need an onclick handler on that button at all.