How to get all selected values of a multiple select box?
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>
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 selected -
map(...)
converts the raw<option>
elements into their respective values