Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an array of currently selected items of a multiple-selection HTML select?

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading