How to get ID of button user just clicked?

JavascriptJqueryHtml

Javascript Problem Overview


> 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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYangView Question on Stackoverflow
Solution 1 - JavascriptGeckoTangView Answer on Stackoverflow
Solution 2 - JavascriptjlacedaView Answer on Stackoverflow
Solution 3 - JavascriptJohn CondeView Answer on Stackoverflow
Solution 4 - JavascriptElliot BonnevilleView Answer on Stackoverflow