views:

34

answers:

2

Hi, I'm trying to use jQuery to make an ajax request based on a selected option.

Is there a simple way to retrieve the selected option id (e.g. "id2") using jQuery?

<select id="my_select">
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>


$("#my_select").change(function() {
    //do something with the id of the selected option
});
+5  A: 

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});
Nick Craver
@kevin - thanks, saw and fixed that after I posted...it's the little things you don't notice until the highlighting kicks in :)
Nick Craver
Very nice. Thanks!
Itamar Bar-Lev
I removed my last comment because it's working fine. I simply made a mistake.
Itamar Bar-Lev
A: 
Mihai Iorga
2 comments here, he already has the DOM element with `this` inside an event handler, no need to perform a lookup again...and might want to pick another variable name, `selectedIndex` would be especially inaccurate here :)
Nick Craver
yes ... sorry ... i was in a hurry ... and selectedIndex variable was in hand ...of course he doesn't need to pass again .. i'll redo
Mihai Iorga