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.
Here's an approach that seems cleaner for my purposes.
First, for any and all forms:
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
Just another solution since no other met my requirements. The advantage is, that click and keypress (enter and space) are detected.
This worked best for me.
I implemented this and I suppose it will do.
and this is the submit button event that sets it up
Thanks for the responses, but this isn't terribly inelegant...
According to this link, the Event object contains a field
Event.target
, which:Returns a string representing the object that initiated the event.
I just created a page testing out what that value is, and it appears as though that representation is for the form itself, not for the button clicked. In other words, Javascript doesn't provide the facility to determine the clicked button.
As far as Dave Anderson's solution, it might be a good idea to test that in multiple browsers before using it. It's possible that it could work fine, but I can't say either way.
One clean approach is to use the click event on each form button. Following is a html form with save,cancel and delete buttons:
Following is the jquery. I send the appropriate 'action' to the same server function depending on which button was clicked ('save' or 'delete'). If 'cancel', is clicked, I just reload the page.
jQuery doesn't seem to provide that data on the submit event. Looks like the method you proposed is your best bet.