Reputation: 3727
HTML:
<select id="leftpane" size="10">
<option id="1" value="one">One</option>
<option id="2" value="two">Two</option>
</select>
jQuery:
$("#leftpane").click(function () {
alert(this.id);
});
In the above code, if I click an item, it will display the id of the select that is "leftpane". What I want is the id of the option that was clicked. I can easily get the value:
alert($(this).val());
But how do I get the id of the option clicked?
Upvotes: 3
Views: 4705
Reputation: 997
Please try this :)
$("#leftpane option").click(function() {
var clickedOptText = $(this).text();
alert(clickedOptText)
});
OR
$("#leftpane option").on("click",function(){
var clickedText = $(this).text();
alert(clickedText);
var clickedValue = $(this).value();
alert(clickedValue);
});
Upvotes: 0
Reputation: 26
this is working i have tried ..........
` $(document).ready(function () {
$("#leftpane option").click(function () {
alert(this.id);
});
}); `
Upvotes: 0
Reputation: 140
You can use following code to get selected elements Id.
$("#leftpane").change(function(){
$(this).find("option:selected").attr("id");
});
OR
$("#leftpane").click(function(){
$(this).find("option:selected").attr("id");
});
Upvotes: 1
Reputation: 173562
I think you should use the change
event instead; it gets triggered whenever a new option is selected:
$("#leftpane").on('change', function () {
var id = this.options[this.selectedIndex].id;
});
Inside the event handler, you use this.options[this.selectedIndex]
to find the selected <option>
element.
Upvotes: 2
Reputation: 94459
Adjust the selector to choose the option
s. This will cause the event handler to be assigned to options instead of the drop down.
$("#leftpane option").click(function () {
alert(this.id);
});
Working Example http://jsfiddle.net/hJdpV/
Upvotes: 3