Reputation: 13166
I have some HTML codes:
<input type="button" id="btn1" class="myButton" value="Button 1"/>
<input type="button" id="btn2" class="myButton" value="Button 2"/>
I need to run a jQuery function whenever user click each button, and I have to do it using their class.
$('.myButton').click(function() {
// do something
});
But what I should to do, depends on the current element Id.
My question is that how can I detect which element called this function? I need to know its id.
Upvotes: 26
Views: 88258
Reputation: 8482
You can use this
to access current element and then this.id
will give you the id
of the current element.
$(document).on('click', '.myButton', function(e) {
alert(this.id);
});
Upvotes: 40
Reputation: 1805
$('.myButton').on('click',(e)=> {
if (e.target.id === "btn1") {
...
}
});
Upvotes: 0
Reputation: 2958
Look at this. You can just use the attr() method to get the id of the clicked element as you bind a click callback to EVERY element with .myButton class.
Upvotes: 2
Reputation: 15958
If you want to keep in jquery context, you could use this snippet:
$('.myButton').click(function() {
alert($(this).attr('id'));
});
With this way you are a bit more flexible.
Upvotes: 27
Reputation: 30666
this
in the event handler is the element that was clicked:
$('.myButton').click(function() {
if (this.id === "btn1") {
...
}
});
Upvotes: 1