Mark Fondy
Mark Fondy

Reputation: 3923

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

Upvotes: 16

Views: 26140

Answers (9)

Badre
Badre

Reputation: 727

Try this :

$('select:#idSelect').val()

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this

$("#sel").find('option:selected').attr('id');

Ideally you should use value attribute for option tags and just use val method to get the selected value from the dropdown element. $("#sel").val();

Upvotes: 3

Yogurt The Wise
Yogurt The Wise

Reputation: 4489

Will the jquery :selected filter work. Something like this...

$("#sel:selected").each(function(){
   alert($(this).attr('id'))
})

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92274

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

Upvotes: 4

Esailija
Esailija

Reputation: 140210

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

$("#sel").change(function(){
   alert( this.options[this.selectedIndex].id );
})

Upvotes: 20

Jakub
Jakub

Reputation: 20475

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

should work.

Upvotes: 21

simshaun
simshaun

Reputation: 21466

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

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227190

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

Upvotes: 12

jrummell
jrummell

Reputation: 43067

Change the id attribute to value and then use .val().

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


var selectedValue = $("#sel").val();

Upvotes: 0

Related Questions