I'm trying to find the value of the submit button that triggered the form to submit
$("form").submit(function() {
});
I could possibly fire a $("input[type=submit]").click() event for each button and set some variable, but that seems less elegant than some how pulling the button off of the the form on submit.
I did try some of the examples provided, but they didn't work for our purposes.
Here's a fiddle to show: http://jsfiddle.net/7a8qhofo/1/
I was faced with a similar issue, and this is how we solved the issue in our forms.
you can try this way with "event.originalEvent.x" and "event.originalEvent.y":
( event )
With a more specific event handler and JQuery, your event object is the button clicked. You can also get the delegating form from this event if needed.
This Doc has everything you need to get started. JQuery Doc.
I leveraged
document.activeElement
as sketched in this answer: How to get the focused element with jQuery?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, thedocument.activeElement
is not set. You'd need to watch out for this yourself, by handlingkeypress
events ininput[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:
I searched and found several ways to get the submit button
name
+value
sent to the server using jQuery + AJAX. I didn't like them very much...One of the bests was hunter's solution presented here!
But I wrote another one myself.
I want to share, because it is good, and, as I needed, it works also with forms loaded via ajax (after document.ready):
Simple! When the submit button is clicked, a hidden field is added to the form, using same
name
andvalue
of the submit button.EDIT: The version below is easier to read. Also, it takes care of removing previously appended hidden fields (in the case of submitting the same form twice, which is perfectly possible when using AJAX).
Improved code: