0

I have some buttons with the same onClick function. Inside this onClick function I want to check which ID is pressed. Each button has a different ID.

How would I go about returning the ID of the button that is clicked?

Rahul
  • 76,197
  • 13
  • 71
  • 125

5 Answers5

0

Without jQuery, it's just the element.id. Here's an example JSFiddle

function clicked(e) {
    alert( this.id );   
}

The above is the callback function for your click event.

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
0
function myFn(){

    // your code;
    alert( this.id );

}

will do the job if you're calling your function like i.e:

var $btn = document.querySelectorAll('button');
for(var i=0; i<$btn.length; i++) $btn[i].addEventListener('click', myFn, false);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

In your button click, pass the id of that button

<button id="btn1" onClick="btnclick(this.id)">button1</button>

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

Else if you are not passing ID as parameter to the click handler

<button id="btn1" onClick="btnclick()">button1</button>

function btnclick(e) {
    e = e || window.event;
    e = e.target || e.srcElement;
    if (e.nodeName === 'BUTTON') {
        alert(e.id);
    }
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

You can pass 'this' to your method to identify the caller.

<button id="1" type="button"onclick="myFunction(this)">Click me!</h1>

and refer to it with id as suggested by LaughDonor

function myFunction(entity)
{  
    alert(entity.id);
}
caburse
  • 156
  • 6
-1

i would use $(this).attr('id') (if you are using jquery) Can you post your code?

If you're not using Jquery, I'd pass the id as a parameter in the onclick function. Without actually seeing your code, it will be harder to tell.

See here for more context.

Community
  • 1
  • 1
deweyredman
  • 1,440
  • 1
  • 9
  • 12