Reputation:
This should be really straight forward.
I'm checking if a form is being submitted using jquery. The form has multiple submit buttons with various values:
<button type="submit" value="foo">Foo</button>
<button type="submit" value="bar">Bar</button>
I would like to find the value of the button that just submitted the form:
$(form).live('submit', function() {
// Get value of submit button
}
Thanks
Upvotes: 18
Views: 44964
Reputation: 16953
$('input[type="submit"]').click(function() {
alert ($(this).val());
}
Upvotes: 1
Reputation: 31250
Bind the event to submit buttons instead of the form and then $(this) would have the reference to the buttons...
$(":submit").live('click', function() {
alert($(this).val());
})
EDIT As of jQuery 1.7 live is deprecated. Use on instead.
$(document).on("click", ":submit", function(e){
alert($(this).val());
});
Upvotes: 26
Reputation: 87
This seems to get the clicked submit button:
jQuery("#TheForm").context.activeElement.name
jQuery("#TheForm").context.activeElement.value
Upvotes: 6
Reputation: 679
I recommend the use of the Firebug Add On, you get a lot of responses to your questions just looking to the data in the console. I realize that in your case you can access the submit value this way:
alert($(this).context.submit.value);
Upvotes: 0
Reputation: 3607
I ended up using the click event on each submit button, as others have suggested. That works fine, and you can return false from them if you want to cancel the submit. Just don't try to also bind the submit event of the form. You could also have each of these handlers call a common submit-handler function, passing their own value as an argument.
Upvotes: 0
Reputation: 1183
You can't if you're using the "submit" event. A form can be submitted without ever hitting a submit button.
In order to obtain which button was clicked, you need to alter your approach by using custom events and marking down which button was actually clicked (creating a selector that can catch click on any of the X buttons in the form). That also requires binding a custom event and prohibiting submit event of the form itself.
Upvotes: 3