How to know which submit button fired the onsubmit event

There is a submitter attribute on SubmitEvent object.

See example:

<!DOCTYPE html>
<html>
<body>
<form action="./test.html" onsubmit="myFunction(event)">
  Enter name: <input type="text" name="fname">
  <button id="firstButton" type="submit">Button 1</button>
  <button id="secondButton" type="submit">Button 2</button>
</form>

<script>
function myFunction(event) {
  // This should log id of the button that was used for submition
  console.log(event.submitter.id); 

  // Prevent sending the form (just for testing)
  event.preventDefault();
}
</script>

</body>
</html>

See https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter


Does having an event listener on each button count as adding code? Otherwise, there's no way to see what button triggered the submit event, unless you want to get down and dirty and calculate the mouse position during the event and compare it to button positions.

Otherwise, the next best thing would be to assign an event handler for the click event of button and assign the name of that button to a variable you can check in the form's submit event.


The "submit" event is not fired by the button, but its fired by the "form". A quick test proves this:

  <form id="myform">
     <input id="email" type="text" value="1st Email" />
     <input id="action1" type="submit" value="Action 1" />
     <input id="action2" type="submit" value="Action 2" />
  </form>

  <script type="text/javascript">

     document.getElementById("myform").onsubmit = function(evt)  {
        var event = evt || window.event;
        alert(event.target.id); // myform
        alert(event.explicitOriginalTarget.id); // action2 (if action2 was clicked)
                                                // but only works in firefox!
     }

  </script>

Although in firefox, you can use event.explicitOriginalTarget property on event to get the input (submit) that was clicked causing the submit event to be fired. (if you want to know)

So best options for you are:

  • Have a different value to your submit buttons OR
  • Have those as normal buttons and click handlers to them via javascript.