I have a HTML select dropdown with multiple
provided, and assign a handler which shows the currently selected elements' index:
document.getElementById("mySelect").onclick = function() {
console.log(this.selectedIndex);
}
<select multiple id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
Which works fine when I select one of the elements only. But I want to return all indexes currently selected.
When I click Apple, Orange and Banana
a return like [0,1,3]
is what I want, but it does not work.
You can use the selectedOptions property.
document.getElementById("mySelect").onclick = function() {
console.log(Array.from(this.selectedOptions).map(option => option.index))
}
<select multiple id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>