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;
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…