How to know which submit button fired the onsubmit event

GetFree picture GetFree · Aug 21, 2010 · Viewed 7.6k times · Source

When you have more than one submit button in a form, is there a way to know which one fired the onsubmit event without adding code to the buttons themselves?


Edit: I need to do the check on the client-side, i.e. with JavaScript.

Answer

naikus picture naikus · Aug 21, 2010

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.