341

How do find the id of the button which is being clicked?

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

function reply_click()
{
}
jewishspiderweb
  • 107
  • 2
  • 11
Bin Chen
  • 54,865
  • 51
  • 136
  • 180

17 Answers17

675

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

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

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

codeherk
  • 1,209
  • 12
  • 24
shamittomar
  • 43,068
  • 12
  • 72
  • 76
  • 3
    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. – X3074861X Aug 08 '13 at 16:30
  • 7
    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 – Denislav Karagiozov Mar 21 '17 at 11:03
  • You don't really want any code in your html, like – Dave Jacoby Jan 31 '19 at 17:24
  • if (this.id == "1") { console.log("btn 1 is Activated"); } – Omar bakhsh Available to work Jul 01 '20 at 01:00
  • Somebody tell me, why some people do not want inline Javascript code? – Brethlosze Apr 27 '21 at 20:13
  • @Brethlosze if your project is small, I guess nobody will complain. If it gets bigger, you want to separate your HTML from your code, so that two different people - the "HTML guy" and the "coder" for example - will be able to work independently. This is even truer when you are working in a big team. – ZioBit May 08 '21 at 13:32
73

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.

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.

For example:

<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>
Charlie Egan
  • 4,095
  • 6
  • 26
  • 47
Jason LeBrun
  • 12,041
  • 2
  • 40
  • 40
  • 2
    what if the buttons are in a repeater and therefore generated dynamically, so you dont know how many buttons you will have? – Amc_rtty Oct 26 '12 at 12:47
  • 4
    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. – Jason LeBrun Oct 26 '12 at 17:33
  • @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? – Arihant Jun 07 '16 at 14:23
  • I know this is an old thread but on my modern browser (FireFox 78) your implementation of _this_ did not work as intended. My function is triggered by an onkeyup event of an input text box, but _this_ was using the _window_ node. Instead, I had to use **_event.srcElement_** – JAX Aug 19 '20 at 18:56
58

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

In the HTML part:

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

In the Javascipt Controller:

function reply_click()
{
    alert(event.srcElement.id);
}

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

Prateek
  • 835
  • 7
  • 6
  • 2
    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! – ejbytes Sep 08 '16 at 23:21
  • @codeling can you share the details of the browser and environment? – Prateek Feb 20 '17 at 14:02
  • @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 Feb 20 '17 at 15:59
  • 4
    FYI: The global event object is available in chrome, not firefox. – DaveEdelstein Oct 10 '17 at 17:55
  • 2
    As of 2021, event.srcElement is deprecated. – Grogu Jan 13 '21 at 00:58
  • 1
    It showed a msg-box with nothing on it.... – gab Apr 27 '21 at 18:22
43

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

You could go for event delegation...

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

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

sdleihssirhc
  • 40,010
  • 5
  • 51
  • 67
  • 1
    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. – Jason LeBrun Jan 28 '11 at 06:03
  • 1
    And the value of the "id" attribute can be any string. It doesn't have to start with a letter. – Jason LeBrun Jan 28 '11 at 06:03
  • @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 Jan 28 '11 at 06:06
  • @Jason Also, [ids can't start with a number](http://www.w3.org/TR/html4/types.html). – sdleihssirhc Jan 28 '11 at 06:07
  • 6
    @sdleihssirhc Actually, you arrogant so-and-so, [that all changes with HTML5](http://mathiasbynens.be/notes/html5-id-class). – sdleihssirhc Jan 28 '11 at 06:08
  • Ah yes, sorry, I was thinking of JavaScript object properties, which can start with a number (which just prevents you from using the . shortcut to access them) – Jason LeBrun Jan 28 '11 at 06:18
  • However, the e attribute will *not* be generated in your example (certainly not in Chrome or Firefox). The text you provide to the onclick attribute inline with HTML is executed as the body of function that receives no parameters, and executes in the context of the clicked-on element. So, within that function you are calling reply_click() explicitly with no parameters, so e will be undefined. However, |this| will refer to the exact DOM element that was clicked, and in IE window.event will work as you mention. – Jason LeBrun Jan 28 '11 at 06:23
  • @Jason Ha ha! Very weird. It turns out that when I tested in Chrome, the first part of that "or" was failing... but Chrome actually creates `window.event` *as well*, so the code was still working! Wacky, wacky event model... – sdleihssirhc Jan 28 '11 at 06:27
  • Thanks this worked for me even when my id were dynamic and no other answer seemed to work. Thanks a lot. – Vinita Mar 04 '21 at 04:16
32
<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;
}
Mohanraj
  • 329
  • 3
  • 2
19
<button id="1" class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>

<script>
$('.clickMe').click(function(){
    alert(this.id);
});
</script>
Adam Simpson
  • 3,261
  • 2
  • 20
  • 26
Jay
  • 3,243
  • 5
  • 23
  • 34
17

How to do it without inline JavaScript

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.

2014 browsers only

<button class="btn" id="b1">Button</button>
<script>
let OnEvent = (doc) => {
    return {
        on: (event, className, callback) => {
            doc.addEventListener('click', (event)=>{
                if(!event.target.classList.contains(className)) return;
                callback.call(event.target, event);
            }, false);
        }
    }
};


OnEvent(document).on('click', 'btn', function (e) {
    window.console.log(this.id, e);
});

</script>

2013 browsers only

<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
    var hasClass = function(el,className) {
        return el.classList.contains(className);
    }
    doc.addEventListener('click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault();
          doSomething.call(e.target, e);
      }
    });
})(document);

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

Cross-browser

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
    var cb_addEventListener = function(obj, evt, fnc) {
        // W3C model
        if (obj.addEventListener) {
            obj.addEventListener(evt, fnc, false);
            return true;
        } 
        // Microsoft model
        else if (obj.attachEvent) {
            return obj.attachEvent('on' + evt, fnc);
        }
        // Browser don't support W3C or MSFT model, go on with traditional
        else {
            evt = 'on'+evt;
            if(typeof obj[evt] === 'function'){
                // Object already has a function on traditional
                // Let's wrap it with our own function inside another function
                fnc = (function(f1,f2){
                    return function(){
                        f1.apply(this,arguments);
                        f2.apply(this,arguments);
                    }
                })(obj[evt], fnc);
            }
            obj[evt] = fnc;
            return true;
        }
        return false;
    };
    var hasClass = function(el,className) {
        return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
    }

    cb_addEventListener(doc, 'click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault ? e.preventDefault() : e.returnValue = false;
          doSomething.call(e.target, e);
      }
    });
})(document);

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>

Cross-browser with jQuery

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

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

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

You can always replace insertHTML with document.write if you don't mind it's drawbacks

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

Sources:

Timo Huovinen
  • 46,329
  • 33
  • 128
  • 127
  • 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? – gabn88 May 30 '16 at 14:25
  • depends on your class naming convention, if the convention is meaningful then it will be as easy to find as onclicks – Timo Huovinen May 31 '16 at 06:01
13

If you don't want to pass any arguments to the onclick function, just use event.target to get the clicked element:

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

function reply_click()
{
    // event.target is the element that is clicked (button in this case).
    console.log(event.target.id);
}
A-Sharabiani
  • 13,270
  • 12
  • 87
  • 109
7

With pure javascript you can do the following:

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

check it On JsFiddle

m7913d
  • 8,353
  • 7
  • 20
  • 47
codercat
  • 21,439
  • 9
  • 56
  • 84
6

You can simply do it this way:

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

Pang
  • 8,605
  • 144
  • 77
  • 113
user3262563
  • 73
  • 1
  • 6
6
<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)
}
gest
  • 291
  • 5
  • 3
3

Button 1 Button 2 Button 3

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;
DisplayName
  • 3,065
  • 5
  • 36
  • 40
XYZ
  • 31
  • 1
3
 <button id="1"class="clickMe"></button>

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

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



$('.clickMe').live('click',function(){

var clickedID = this.id;

});
tilak
  • 4,037
  • 5
  • 31
  • 44
2

Sorry its a late answer but its really quick if you do this :-

$(document).ready(function() {
  $('button').on('click', function() {
     alert (this.id);
  });
});

This gets the ID of any button clicked.

If you want to just get value of button clicked in a certain place, just put them in container like

<div id = "myButtons"> buttons here </div>

and change the code to :-

 $(document).ready(function() {
      $('.myButtons button').on('click', function() {
         alert (this.id);
      });
    });

I hope this helps

wayneuk2
  • 140
  • 10
  • 1
    I think myButtons is an id and you using it as a class selector in jquery with a dot(.) I think this should be start with #. – shashi verma Dec 22 '18 at 07:39
2

This will log the id of the element that's been clicked: addFields.

<button id="addFields" onclick="addFields()">+</button>

<script>

function addFields(){ 
    console.log(event.toElement.id)
}

</script>
alecbaldwin
  • 162
  • 9
1

Although it's 8+ years late, in reply to @Amc_rtty, to get dynamically generated IDs from (my) HTML, I used the index of the php loop to increment the button IDs. I concatenated the same indices to the ID of the input element, hence I ended up with id="tableview1" and button id="1" and so on.

$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";

In the javascript, I stored the button click in a variable and added it to the element.

function loadDoc(e) {
  var btn = e.target.id;
  var xhttp = new XMLHttpRequest();
  var page = document.getElementById("tableview"+btn).value;
  
  //other Ajax stuff
  }
Mark Lee
  • 103
  • 7
0

This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)

function reply_click(e) {
  console.log(e.target.id);
}
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241