1

The form uses several submit buttons with different formaction. When the button is clicked, the submit event is raised. Is it possible to find out from the event handler which button was pressed?

<html>
        <body>
            <form>
                <button formaction="1">1</button>
                <button formaction="2">2</button>
            </form>
            <script>
                var form = document.querySelector('form');
                form.addEventListener('submit', function(event) {
                    event.preventDefault();
                    var formaction = '?';
                    alert(formaction);
                });
            </script>
        </body>
    </html>

UPD. Tested variants:

event.target - <form>
event.srcElement - <form>
event.currentTarget - <form>
event.originalTarget - udefined (FF <form>)
document.activeElement - <button> (Safari <body>)
event.explicitOriginalTarget - udefined (FF <button>)
temoffey
  • 121
  • 4
  • has Jquery answers, but you should figure it ut: https://stackoverflow.com/questions/2066162/how-can-i-get-the-button-that-caused-the-submit-from-the-form-submit-event or https://stackoverflow.com/questions/3577469/form-onsubmit-determine-which-submit-button-was-pressed – epascarello Jan 28 '19 at 14:17

2 Answers2

0

You could add different click handlers for multiple buttons <input type="button"/> but if you really need to have the submit event triggered I would recommend using data tags

Add this to your input tag data-formaction="exampleValue"

You can access the exampleValue value using: event.target.dataset.formaction inside your event handler

-1

Click events generally have two targets - .target which is the element that was clicked on, and .currentTarget, which is the element that caught the event (in this case, the form).

For your purposes, I suggest using event.target. A common pattern is to give your button a name attribute, so you can find do event.target.name to figure out which button was pressed.

Bear in mind this will go a bit wrong if your button contains anything complex, like an icon, because then it's the icon element will be the target.

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20