I'm trying to find the value of the submit button that triggered the form to submit
$("form").submit(function() {
});
I could possibly fire a $("input[type=submit]").click() event for each button and set some variable, but that seems less elegant than some how pulling the button off of the the form on submit.
Best Answer
I leveraged
document.activeElement
as sketched in this answer: How to get the focused element with jQuery?I take advantage of the fact, that the button is always the focused element after clicking it. This will not work, if you do a
blur()
right after the click.@Doin has spotted another drawback. If a user submits the form via
enter
in a text field, thedocument.activeElement
is not set. You'd need to watch out for this yourself, by handlingkeypress
events ininput[type="text"]
and similar.Update 2017-01: For my library Hyperform I chose not to use
activeElement
but to catch all events, that lead to form submission. The code for this is on Github.If you happen to use Hyperform, this is how you would access the button that triggered the submit: