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