Reputation: 677
I am very new to jQuery. Below is part of my code
<div class = 'buttons'>
<span>
<input type='button' value='BUTTON1' id='button1'>
</span>
<span>
<input type='button' value='BUTTON2' id='button2'>
</span>
</div>
Using jquery, I would like to print the id of the button clicked. I tried the following:
$(".buttons > span").click(function () {
alert("YOU CLICKED" + this.id);
});
But I think this is referring to the span object. This is weird because how come the span object has a click event? Or all jquery objects have "click"? How do I get the id of the button in the span?
Thank You.
Upvotes: 4
Views: 6499
Reputation: 33572
Here is another way to do that by capturing the event's target element:
$(".buttons > span").click(function (e) {
alert("YOU CLICKED" + e.target.id);
});
Upvotes: 4
Reputation: 2091
What about this?
$(".buttons > span > input").click(function () {
alert("YOU CLICKED" + this.id);
});
Upvotes: 6
Reputation: 97672
$(".buttons > span").click(function () {
alert("YOU CLICKED" + $('input[type=button]',this).prop('id'));
});
or you could bind the event to the button itself
$(".buttons > span > input[type=button]").click(function () {
alert("YOU CLICKED" + this.id);
});
Upvotes: 1