Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }); 
like image 709
botmsh Avatar asked May 22 '10 14:05

botmsh


People also ask

How do I get the selected option ID?

Getting the selected ID using the selectedIndex and options properties # The options property returns an HTMLOptionsCollection , an array-like collection of options for a select element. You can pair it with the selectedIndex property to get the selected option . Then, you can use the id property to get its ID.

How do I get the text value of a selected option jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How do you check if a dropdown is selected in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });


2 Answers

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

$("#my_select").change(function() {   var id = $(this).children(":selected").attr("id"); }); 
like image 176
Nick Craver Avatar answered Sep 24 '22 06:09

Nick Craver


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

like image 40
Mihai Iorga Avatar answered Sep 24 '22 06:09

Mihai Iorga