How to get ID of button user just clicked? [duplicate]

Solution 1:

$("button").click(function() {
    alert(this.id); // or alert($(this).attr('id'));
});

Solution 2:

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/

Solution 3:

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>

Solution 4:

$("button").click(function() {
    alert(this.id);
});