How to get all selected values from a multi-select element with JavaScript?

Sometimes, we want to get all selected values from a multi-select element with JavaScript.

In this article, we’ll look at how to get all selected values from a multi-select element with JavaScript.

How to get all selected values from a multi-select element with JavaScript?

To get all selected values from a multi-select element with JavaScript, we use the selectedOptions property.

For instance, we write

<select id="select-meal-type" multiple="multiple">
  <option value="1">Breakfast</option>
  <option value="2" selected>Lunch</option>
  <option value="3">Dinner</option>
  <option value="4" selected>Snacks</option>
  <option value="5">Dessert</option>
</select>

to add a multi-select box.

Then we write

const options = document.getElementById("select-meal-type").selectedOptions;
const values = Array.from(options).map(({ value }) => value);
console.log(values);

to get the select element by ID.

We get the selected options with selectedOptions.

Then we convert the selectedOptions into an array with Array.from.

And we call map with a callback to map the selected option objects to get the value from them.

The value has the value attribute value.

Conclusion

To get all selected values from a multi-select element with JavaScript, we use the selectedOptions property.