How to get all selected values from <select multiple=multiple>?
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select
is a reference to the <select>
element.
To break it down:
[...select.options]
takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider usingArray.from()
)filter(...)
reduces the options to only the ones that are selectedmap(...)
converts the raw<option>
elements into their respective values
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
The usual way:
var values = $('#select-meal-type').val();
From the docs:
In the case of
<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option;