How to get all selected values from a multiple select with JavaScript?

Spread the love

Sometimes, we want to get all selected values from a multiple select with JavaScript.

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

How to get all selected values from a multiple select with JavaScript?

To get all selected values from a multiple select with JavaScript, we use querySelector.

For instance, we write

const selected = document.querySelectorAll("#select-meal-type option:checked");
const values = Array.from(selected).map((el) => el.value);

to select all the selected options from the select element with ID select-meal by calling querySelector with "#select-meal-type option:checked".

Then we convert selected to an array with Array.from and then call map with a callback that returns the selected value from each element.

Conclusion

To get all selected values from a multiple select with JavaScript, we use querySelector.

Leave a Reply

Your email address will not be published.