Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

forms

People also ask

How do you check if a form is submitted in jquery?

$("#something-%"). submit(function(e) { e. preventDefault(); $("#some-span"). html(data); });

What happens when submit button is clicked?

The form will be submitted to the server and the browser will redirect away to the current address of the browser and append as query string parameters the values of the input fields.

Which method will get executed on clicking submit button?

When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method.


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."