botmsh
botmsh

Reputation: 1366

Get the selected option id with jQuery

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
});

Upvotes: 92

Views: 271552

Answers (4)

jk121960
jk121960

Reputation: 873

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

Upvotes: 3

wild_nothing
wild_nothing

Reputation: 3051

$('#my_select option:selected').attr('id');

Upvotes: 25

Mihai Iorga
Mihai Iorga

Reputation: 39724

var id = $(this).find('option:selected').attr('id');

then you do whatever you want with selectedIndex

I've reedited my answer ... since selectedIndex isn't a good variable to give example...

Upvotes: 29

Nick Craver
Nick Craver

Reputation: 630627

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

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Upvotes: 236

Related Questions