66

Possible Duplicate:
Getting the ID of the element that fired an event using JQuery

I have many buttons with ID attribute.

<button id="some_id1"></button>
<button id="some_id2"></button>
<button id="some_id3"></button>
<button id="some_id4"></button>
<button id="some_id5"></button>

Assume the user clicks on some button, and I want to alert this ID of the button the user just clicked on.

How can I do this via JavaScript or jQuery?

I want to get the ID of button user just clicked.

Community
  • 1
  • 1
Yang
  • 8,580
  • 8
  • 33
  • 58

4 Answers4

150
$("button").click(function() {
    alert(this.id); // or alert($(this).attr('id'));
});
GeckoTang
  • 2,697
  • 1
  • 16
  • 18
37

With pure javascript:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}​

http://jsfiddle.net/TKKBV/2/

jlaceda
  • 866
  • 6
  • 11
26

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>
Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
John Conde
  • 217,595
  • 99
  • 455
  • 496
13
$("button").click(function() {
    alert(this.id);
});
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123