jQuery Tip - Getting Select List Values
Tags: jQuery, Tutorial | Written on 22/7/08

Chris Hartjes asked me a simple question today, but it is worth noting because I have asked the same before, "How do you get the current value from a select list?"
To get the current value is very simple using val().
JavaScript:
$('#selectList').val();
But sometimes you may need to get the selected option's text. This is not as straight forward. First, we get the selected option with :selected selector. Then once we have the option, we can get the text with the function, text().
JavaScript:
$('#selectList :selected').text()
View Demo:
Note on July 23 @9:14AM: HoyaSaxa93 wrote in to ask how to get values from select multiples. I will create the demo and code below. This would be how to set a select multiple to an array called, "foo".
JavaScript:
var foo = []; $('#multiple :selected').each(function(i, selected){ foo[i] = $(selected).text(); });
Comments
If you want a real array, I'd use this:
$.map($('#foo :selected'), function(e) { return $(e).text(); })
There you'll have ["One", "Two", "Three"]
val()will work just fine to get an array of values, but to get an array of text is a little different. I added code to the bottom of the article that describes how to get the selected options text to an array.rd: I don't understand
$.mapenough to comment on it, I will have to look into that!<select id="s1">
<option value="">1</option>
<option value="1">2</option>
<option value="4">3</option>
<option value="5">4</option>
</select>
<script>
$("#s1").val("4");
</script>
It doesn't work but
$("#s1").val("1");
works just fine. Strange behaviour.
$("#s1").val("4");works to select the fourth option.$("#s1").val("1");or$("#s1").val("2");will select the second option because you don't have a value set for the first option. To select the first option use,$("#s1").val("0");.$('#s1')[0].selectedIndex = 0;. I personally have not usedvalto set the value of a select list before. I just tested it above based on your comment.$("#selectList option[@value=2]").remove();This would grab select list with id, "selectList" and find an option within it that has value, "2" - then remove it.