How to get an array like ["Apple", "Orange"]
of currently selected items of a multiple-selection HTML select
?
We could probably parse the <option>
HTML of s.selectedOptions
but there is surely a more standard way:
var s = document.getElementById('mySelect');
document.onclick = () => {
console.log(s.selectedIndex);
console.log(s.selectedOptions);
};
<select multiple id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
CodePudding user response:
Currently there is no better way but to map
over the selectedOptions
.
document.getElementById('mySelect').addEventListener('change', function(e){
console.clear();
const selectedVals = [...this.selectedOptions].map(o => o.value);
console.log(selectedVals);
});
<select multiple id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
CodePudding user response:
Checking the value of each option element(option.selected) can be a method, but using the selectedOptions method of the select element is also a standard method.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions
An option is considered selected if it has an HTMLOptionElement.selected attribute.
Additionally, if you want a simpler code, please refer to the link below. https://stackoverflow.com/a/49684109/11618421