Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>

<script type="text/javascript">
function reply_click(clicked_id)
{
    alert(clicked_id);
}
</script>

Brother , you are the only person on the internet that managed to interpret for me the way this works. Using a variable in the function name and than using another in the actual function script made absolutely no sense to me ! In one short sentence you explained to me that the variable we put in the function brackets () and the one we use on the function declaration are the same thing , just passed on AS ! This is brilliant ! Thank you my lord for the wisdom you have bestowed upon me

I just wanted to note, for anyone getting a null reference exception using JQuery's event.target.id (for me, both Firefox and IE were throwing it), this is a great solution that works in all three major browsers.

This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

You need to send the ID as the function parameters. Do it like this:

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
    $(document).on('click', '.click-me', function(e){
      doSomething.call(this, e);
    });
})(jQuery);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
document.write
insertHTML

Here is a jsfiddle For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

I'm always wondering how events can be as efficient (performance-wise) as inline onclicks. I guess they must be harder to keep track of?

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

depends on your class naming convention, if the convention is meaningful then it will be as easy to find as onclicks

it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it. Here is my way of attaching events to buttons. I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>

function reply_click(obj)
{
var id = obj.id;
}
Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

<script type="text/javascript">
var reply_click = function()
{
    alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>

@JasonLeBrun I don't know what is the id of the element that I am gonna click. That's what I am looking for. A code draws a SVG element and when I click on it, I need to know it's "id" attribute. If and how can this code be used?

In general, things are easier to keep organized if you separate your code and your markup. Define all of your elements, and then in your JavaScript section, define the various actions that should be performed on those elements.

There are a number of ways you could handle that. For example, generate the javascript dynamically. Or, add the same class to all of the buttons, and then iterate through all buttons with that class name and attach the handler that way.

When an event handler is called, it's called within the context of the element that was clicked on. So, the identifier this will refer to the DOM element that you clicked on. You can then access attributes of the element through that identifier.

what if the buttons are in a repeater and therefore generated dynamically, so you dont know how many buttons you will have?

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<div onClick="reply_click()">
    <button id="1"></button>
    <button id="2"></button>
    <button id="3"></button>
</div>

function reply_click(e) {
    e = e || window.event;
    e = e.target || e.srcElement;
    if (e.nodeName === 'BUTTON') {
        alert(e.id);
    }
}

(I think the id attribute needs to start with a letter. Could be wrong.)

...but that requires you to be relatively comfortable with the wacky event model.

@Jason Actually, in all the good modern browsers, the e argument is generated automatically. If it isn't, then we must be dealing with IE6-8, which instead provides that useful object via window.event.

@sdleihssirhc Actually, you arrogant so-and-so, that all changes with HTML5.

And the value of the "id" attribute can be any string. It doesn't have to start with a letter.

This won't work. You've specified code in the onclick attribute that calls reply_click with no arguments. So, no event argument will be passed to the function.

You could go for event delegation...

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
TypeError: event is undefined
function reply_click()
{
    alert(event.srcElement.id);
}

@Prateek Firefox, latest. I only needed the source, so I worked around it now by passing this as parameter in onClick (actually, not using onClick but onChange, is that maybe the problem?). I've also checked around a bit and there seems to be a lot of confusion about this event variable going around - is it an "implicit" parameter or does it have to be stated explicitly as argument (i.e. function reply_click(event), which I've also seen in some locations)? Is it only available when assigning the event listener via addEventListener...? I've played around, but couldn't get it to work.

@codeling can you share the details of the browser and environment?

I like this idea for dynamic functionality. I'm working on adding functions to a dynamic DB using PHP/MySQL and JS; this works out well for adding a specific function to specific dynamic classes. Thanks!

This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.

USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1"class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>

$('.clickMe').click(function(){
    var clickedID = this.id;
});
Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


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);
    };
}

With pure javascript you can do the following:

Your code says: Uncaught TypeError: Cannot set property 'onclick' of undefined

Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

function reply_click()
{
   console.log(window.event.target.id)
}
Note
Rectangle 27 0

html JavaScript onClick to get the ID of the clicked button?


<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
   function showId(obj) {
        var id=obj;
        alert(id);
   }

I think this should be the accepted answer, and "(this.id)" worked for me just now in FF, IE, and Chrome.

You can simply do it this way:

You could cut out the var id=obj; and just have alert(obj);

Note