简体   繁体   中英

How to track the initiator of the submit event in javascript?

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>)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM