H. Ferrence
H. Ferrence

Reputation: 8106

How to detect which submit button is clicked in jquery

If I have 2 submit buttons on my form, is it possible to detect which one was clicked in jquery?

<input name="submit" type="submit" value="Button 1">
<input name="submit" type="submit" value="Button 2">

This is consistently returning "Button 1"

alert($("input[name=submit]").val());

Upvotes: 0

Views: 136

Answers (3)

Dylan Grech
Dylan Grech

Reputation: 182

The best option is to have unique ids for each button and you could do this:

$('input').on('click', function(){
    alert(this.id);
});

else if you want to keep your current structure and return the value you need this:

$('input').on('click', function(){
    // the value inside attr() can be any property of the element
    alert($(this).attr('value'));
});

Upvotes: 0

TimCodes.NET
TimCodes.NET

Reputation: 4699

You don't necessarily need unique ids...using your supplied HTML:

$("input[type=submit]").click(function() {
   alert($(this).val());
});

Edit: I agree you should change the name on one of the buttons though

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

You need to have unique IDs:

<input id="submit1" name="submit" type="submit" value="Button 1">
<input id="submit1" name="submit" type="submit" value="Button 2">

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

http://www.w3schools.com/tags/att_global_id.asp

Upvotes: 0

Related Questions