I have a select element on my web page that allows the user to select multiple options. I want to obtain an array with the values of all the options that are currently selected.
I have tried using the selectedOptions property of the select element, but it only gives me the first selected option.
2
Answers
The selectedOptions property of the select element should give you a list of all the currently selected options, not just the first one.
This property returns an HTMLCollection of option elements that are currently selected in the select element.
Here’s an example of how you can use it to get an array of the values of all selected options:
document.getElementById("your-select-element-id") gets the select element with the specified ID. Use querySelector() or whatever you like instead of getElementById().
Array.from(selectElement.selectedOptions) converts the HTMLCollection of selected options into an array.
selectedOptions.map(option => option.value) creates a new array with the values of all selected options.