Reputation: 15108
<select id="abc" multiple="multiple">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">C</option>
</select>
I wish to retrieve all selected values.
No matter what I try it seems to only give me the value of the selected item that is lowest in the list. So if I select A, B, and C it will only return C.
These are the things I have tried:
$('#abc').val()
$('#abc').text()
$('#abc :selected').val()
$('#abc :selected').text()
$('#abc option:selected').val()
$('#abc option:selected').text()
The version of jQuery I am using is v1.9.1
Upvotes: 1
Views: 171
Reputation: 82231
You need to loop through all selected element within select using .each()
to get access them individually:
$('#abc :selected').each(function(){
console.log($(this).text());
});
or to get the values in array
var selectedvals = $('#abc').val();
Upvotes: 3
Reputation: 24638
For a multiple select when this
references the select
element, you cannot use this.value
as that will return only one value. As @MilindAnantwar has noted above $(this)
will return an array. If you were interested in a comma-delimited string rather than an array you can use the join()
array method to join the various values into a string:
var selectedOpts = $( '#abc' ).val().join( ',' );
Otherwise you would have to access the elements by array notation [0], [1], .... [n-1]
.
Upvotes: 1
Reputation: 74738
You can use .map()
to store the values in an array and use it:
var vals = $('#abc :selected').map(function(){
return this.value;
}).get();
console.log(vals);
or this way:
var vals = [];
$('#abc :selected').each(function(){
vals.push(this.value);
});
console.log(vals);
Upvotes: 1
Reputation: 104775
You can do:
var values = $("#abc option:selected").map(function() {
return this.value;
}).get();
Upvotes: 1