Seemed odd I couldn\'t find this one already asked, but here it goes!
I have an html as follows:
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;
$('#select-meal-type :selected')
will contain an array of all of the selected items.
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
Works everywhere without jquery:
var getSelectValues = function (select) {
var ret = [];
// fast but not universally supported
if (select.selectedOptions != undefined) {
for (var i=0; i < select.selectedOptions.length; i++) {
ret.push(select.selectedOptions[i].value);
}
// compatible, but can be painfully slow
} else {
for (var i=0; i < select.options.length; i++) {
if (select.options[i].selected) {
ret.push(select.options[i].value);
}
}
}
return ret;
};
If you need to respond to changes, you can try this:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions)
is needed because e.target.selectedOptions
returns a HTMLCollection
, not an Array
. That call converts it to Array
so that we can then apply the map
function, which extract the values.
Unless a question asks for JQuery the question should be first answered in standard javascript as many people do not use JQuery in their sites.
From RobG How to get all selected values of a multiple select box using JavaScript?:
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;
}
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);