Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current selected option

<select id="sel">
    <option id="1">aa</option>
    <option id="2">bb</option>
    <option id="3">cc</option>
</select>

$("#sel").change(function(){
   alert($(this).children().attr('id'))
})

LIVE: http://jsfiddle.net/cxWVP/

How can i get current selected option ID? Now always show me id="1".

like image 243
Mark Fondy Avatar asked Jan 10 '12 19:01

Mark Fondy


People also ask

What do you use to get the currently selected option in a select box in JavaScript?

var yourSelect = document. getElementById("your-select-id"); alert(yourSelect. selectedOptions[0]. value);

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


4 Answers

$('#sel').change(function(){
   alert($(this).find('option:selected').attr('id'));
});

should work.

like image 52
Jakub Avatar answered Oct 16 '22 22:10

Jakub


http://jsfiddle.net/cxWVP/1/

$("#sel").change(function(){
   alert( this.options[this.selectedIndex].id );
})
like image 44
Esailija Avatar answered Oct 16 '22 21:10

Esailija


<option> tags should have a value attribute. When one is selected, you get it's value using $("#sel").val().

<select id="sel">
    <option value="1">aa</option>
    <option value="2">bb</option>
    <option value="3">cc</option>
</select>

$("#sel").change(function(){
   alert($(this).val())
});

DEMO: http://jsfiddle.net/yPYL5/

like image 33
Rocket Hazmat Avatar answered Oct 16 '22 22:10

Rocket Hazmat


http://jsfiddle.net/ugUYA/

To get the selected option inside a select element, you can use selectedIndex, then you can use the options array to get to the selected option object

$("#sel").change(function(){
   alert( this.options[this.selectedIndex].id )
})
like image 44
Juan Mendes Avatar answered Oct 16 '22 22:10

Juan Mendes