Search code examples
javascriptdom-eventsdhtml

How to know which submit button fired the onsubmit event


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.


Solution

  • 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