How to know which submit button fired the onsubmit event
Asked Answered
I

6

11

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.

Isla answered 21/8, 2010 at 17:54 Comment(0)
M
2

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

Minima answered 29/6, 2022 at 14:17 Comment(0)
S
5

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.
Saccharify answered 21/8, 2010 at 18:6 Comment(2)
Thanks. I thought of the onclick handlers. It seems there is no clean way (at least not cross-browser)Isla
I'm really surprised this functionality is available, but after coming across this question (and several similar ones), it looks like it just plain isn't there. Lame.Morocco
M
2

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

Minima answered 29/6, 2022 at 14:17 Comment(0)
A
1

There are a couple of ways that I can think of.

You can use different values, and your unobtrusive javascript can help with it.

One discussion on this approach (using different values for each button) is here:

http://www.chami.com/tips/internet/042599I.html

I tend to go with using different name attributes for each button.

A blog on that is here: http://www.codetoad.com/javascript/multiple.asp

I don't follow either of these, which approach will work best is going to depend on different factors, such as, are you handling the submit buttons in javascript, or will the server get the form, then have to figure out what the user wanted.

Personally, I prefer to use the ajax approach, now, where I just attach events to the buttons after the page is loaded, using unobtrusive javascript, and then based on the user choice call out to the correct function, but that depends on whether you can add a script link to the html page.

UPDATE:

In order to do this with javascript, the simplest way is to attach an event on the click of the button, and then look at the name to decide how to handle it.

In actuality, the form never truly has to be submitted to the server, but you can handle everything in the background by wrapping up the parameters (options) and sending them to the server, and let the user know the results.

Avatar answered 21/8, 2010 at 18:1 Comment(1)
Yes, different names is the way to go. Basing the check on the values is conceptually wrong since those values are part of the GUI.Isla
C
1

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.

Corm answered 21/8, 2010 at 18:6 Comment(1)
I was afraid of that. What a shame.Isla
H
1

Sorry to warm up this very old thread. The question hadn't been answered here but only approaches for practical workarounds have been given here before.

But the event-object does carry information about which object has initiated it. In a handler b4submit(e) you can get the submit-button like this:

function b4submit(e) {
    var but = e.originalEvent.explicitOriginalTarget;
    ...
}

And but is an HTML Object with all the attributes you've assigned it with, like name, id, value etc.

I came across this after some debugging, and I thought it might be of a wider interest as a clean solution for this issue.

Haemorrhage answered 6/5, 2016 at 12:55 Comment(1)
The accepted answer already mentions explicitOriginalTarget. It's a mozilla-specific property.Isla
T
1

For me the simplest option that worked for me is to use document.activeElement if you want to get the id use document.activeElement.id if you want to get the text content you can simply put document.activeElement.textContent

  const onSubmit = () => {
    console.log('document.activeElement', document.activeElement.id)
    if (document.activeElement.textContent === 'Suivant') {
      handleNext()
      return
    }
    if (document.activeElement.textContent === 'Confirmer') {
      console.log('Payer')
      return
    }
  }
Tevet answered 23/4, 2022 at 15:0 Comment(2)
Clever trick. Have you checked if it works consistently across all modern browsers (Chromium, Firefox, Safari)?Isla
I have tested for Edge, Chrome, Opera only. But normally it should work for others, give it a try and let us know :).Tevet

© 2022 - 2024 — McMap. All rights reserved.