Get the selected option id with jQuery

JqueryDomJquery Selectors

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

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

Solution 2 - Jquery

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...

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbotmshView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryMihai IorgaView Answer on Stackoverflow
Solution 3 - Jquerywild_nothingView Answer on Stackoverflow
Solution 4 - Jqueryjk121960View Answer on Stackoverflow