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

时间:2021-03-16 21:20:25

本文转自:http://*.com/questions/5721724/jquery-how-to-get-which-button-was-clicked-upon-form-submission

$(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");
    });
});

 

 

 

 

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

This was helpful, to get the id of the activeElement, I did $(document.activeElement).attr('id');

 
For what it's worth, you don't need to use jQuery to get the id - it's even simpler to use pure Javascript: document.activeElement.id