Sometimes, we want to get the currently selected option in a select with JavaScript.
In this article, we’ll look at how to get the currently selected option in a select with JavaScript.
How to get the currently selected option in a select with JavaScript?
To get the currently selected option in a select with JavaScript, we use the selectedIndex property.
For instance, we write
const yourSelect = document.getElementById("your-select-id");
console.log(yourSelect.options[yourSelect.selectedIndex].value);
to select the select element with getElementById.
Then we get the selected option element with yourSelect.options[yourSelect.selectedIndex].
And we get its value attribute value with value.
Conclusion
To get the currently selected option in a select with JavaScript, we use the selectedIndex property.