jQuery: how to get which button was clicked upon form submission?

I asked this same question: How can I get the button that caused the submit from the form submit event?

I ended up coming up with this solution and it worked pretty well:

$(document).ready(function() {
    $("form").submit(function() { 
        var val = $("input[type=submit][clicked=true]").val();
        // DO WORK
    });
    $("form input[type=submit]").click(function() {
        $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});

In your case with multiple forms you may need to tweak this a bit but it should still apply


I found that this worked.

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );
    });
}

This works for me:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}

When the form is submitted:

  • document.activeElement will give you the submit button that was clicked.

  • document.activeElement.getAttribute('value') will give you that button's value.

Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."


Here's the approach that seems cleaner for my purposes.

First, for any and all forms:

$('form').click(function(event) {
  $(this).data('clicked',$(event.target))
});

When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.

Then, in $('form').submit(), you can inquire what was last clicked, with something like

if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();