Sometimes, we want to get the selected values of a multiple select element on change with JavaScript.
In this article, we’ll look at how to get the selected values of a multiple select element on change with JavaScript.
How to get the selected values of a multiple select element on change with JavaScript?
To get the selected values of a multiple select element on change with JavaScript, we can get all the options from the selectedOptions
property of the select element.
For instance, we write:
<select multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
to add a multi-select element.
Then we write:
const select = document.querySelector('select')
select.onchange = (e) => {
const selectedVals = [...e.target.selectedOptions].map(o => o.value)
console.log(selectedVals)
}
to select the select element with querySelector
.
We then set the select.onchange
property to a function that gets all the selected options.
To do this, we get all the selected options with e.target.selectedOptions
.
And then we spread them into an array and call map
with a callback that returns the value
from each selected option.
Conclusion
To get the selected values of a multiple select element on change with JavaScript, we can get all the options from the selectedOptions
property of the select element.