1

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>
Basj
  • 41,386
  • 99
  • 383
  • 673
  • Does this answer your question? [How to get all selected values of a multiple select box?](https://stackoverflow.com/questions/5866169/how-to-get-all-selected-values-of-a-multiple-select-box) – stdob-- Oct 04 '22 at 15:06
  • @stdob-- Most answers of this linked question are outdated, the accepted answer here is far better for nowadays (2022) IMHO. – Basj Oct 04 '22 at 16:28

2 Answers2

4

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>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thanks @Unmitigated. What does the `[...this.selectedOptions]` syntax do? I don't remember. – Basj Oct 04 '22 at 15:13
  • 1
    @Basj It converts the `selectedOptions` into an array (using spread syntax). – Unmitigated Oct 04 '22 at 15:15
  • Thanks for the name which I didn't know, here I found it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – Basj Oct 04 '22 at 15:19
0

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

bae
  • 19
  • 3