How would I get the second value in a dropdown list using javascript or jquery?
<select id='dropdown'>
<option selected>Any</option>
<option>2</option>
<option>3</option>
</select>
e.g. i would like to get the value of number 2 in the dropdown
How would I get the second value in a dropdown list using javascript or jquery?
<select id='dropdown'>
<option selected>Any</option>
<option>2</option>
<option>3</option>
</select>
e.g. i would like to get the value of number 2 in the dropdown
Share Improve this question asked May 12, 2013 at 16:12 Rawand HawizRawand Hawiz 31 silver badge2 bronze badges 2- Are you trying to select the item after the selected option or just the second option? – Ivan Drinchev Commented May 12, 2013 at 16:15
-
There is no value defined for any of the options. Do you mean to take
text
orvalue
? – Kailash Yadav Commented May 12, 2013 at 16:19
5 Answers
Reset to default 4Neither of those options has a value. (Actually, see note below.) You can get the text like this:
var text = $("#dropdown")[0].options[1].text;
Or without jQuery:
var text = document.getElementById("dropdown").options[1].text;
Live Example | Live Source
Or you can use .value
instead of .text
, as the option
elements will default their value
property if you don't give them a value
attribute. (You can't select them using a value=
selector, but the property is defaulted.)
To get the second
value in a dropdown list using jquery, you can do this using .eq():
var text = $("#dropdown option").eq(1).text();
In order, to get the n
th number value in the dropdown list, you can do this:
var text = $("#dropdown option").eq(n - 1).text();
Try this
JS CODE
$(function(){
alert($('#dropdown option').eq(1).val());
});
LIVE DEMO
Why not try this so easy to understand then :eq(n)
http://jsfiddle/q9qCR/2/
$('#dropdown option:nth-child(2)').val()
Try
$(document).ready(function() {
alert($("#dropdown option").eq(1).text());
});