69

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.

0

4 Answers 4

154
$("button").click(function() { alert(this.id); // or alert($(this).attr('id')); }); 
Sign up to request clarification or add additional context in comments.

Comments

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/

3 Comments

Do you know how to do this in asp.net ?
@mutiemule ASP.NET is a server-side technology
sorry @mutiemule, I'm not too familiar with ASP.NET but there should be a way to inject js into the html that you render out similar to templates in express-handlebars.
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> 

Comments

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

3 Comments

Why wrap and immediately unwrap ($(this)[0]) when just this.id will do?
There's no need to jQueryify this. Access the DOM element's id property directly like in @GeckoTang's answer.
@AndrewWhitaker I See no difference ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.