How can I get the button that caused the submit from the form submit event?
I leveraged document.activeElement
as sketched in this answer: How to get the focused element with jQuery?
$form.on('submit', function() {
var $btn = $(document.activeElement);
if (
/* there is an activeElement at all */
$btn.length &&
/* it's a child of the form */
$form.has($btn) &&
/* it's really a submit element */
$btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
/* it has a "name" attribute */
$btn.is('[name]')
) {
console.log("Seems, that this element was clicked:", $btn);
/* access $btn.attr("name") and $btn.val() for data */
}
});
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, the document.activeElement
is not set. You'd need to watch out for this yourself, by handling keypress
events in input[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:
$(form).on('submit', function(event) {
var button = event.submittedVia;
});
I implemented this and I suppose it will do.
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
and this is the submit button event that sets it up
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Thanks for the responses, but this isn't terribly inelegant...