Espen
Espen

Reputation: 3727

Get the id of clicked option in a select

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

Answers (6)

Vishal P Gothi
Vishal P Gothi

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

user2427472
user2427472

Reputation: 26

this is working i have tried .......... 

` $(document).ready(function () {
      $("#leftpane option").click(function () {
        alert(this.id);
          });
    }); `

Upvotes: 0

Tushar
Tushar

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

Ja͢ck
Ja͢ck

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

Khadim Ali
Khadim Ali

Reputation: 2598

Try this:

$("#leftpane option:selected").prop('id');

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

Adjust the selector to choose the options. 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

Related Questions