I have a <select>
element with the multiple
attribute. How can I get this element's selected values using JavaScript?
Here's what I'm trying:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
You can use
[].reduce
for a more compact implementation of RobG's approach:Riot js code
Check-it Out:
HTML:
JQUERY:
CLICK HERE TO SEE THE DEMO
Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptions property:
In detail,
selectedOptions
returns a list of selected items....
is spread syntax. It expands theHTMLCollection
's elements.[...]
creates a mutableArray
object from these elements, giving you an array ofHTMLOptionElements
.map()
replaces eachHTMLObjectElement
in the array (here calledoption
) with its value (option.value
).Dense, but it seems to work.
Watch out,
selectedOptions
isn't supported by IE!ES6
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 valuesMy template helper looks like this: