Sometimes, we want to get JavaScript select box’s selected text.
In this article, we’ll look at how to get JavaScript select box’s selected text.
How to get JavaScript select box’s selected text?
To get JavaScript select box’s selected text, we can use the select element’s options and selectedIndex properties.
For instance, we write
const sel = document.getElementById("selectBox");
const text = sel.options[sel.selectedIndex].text;
to select the select element with getElementById.
Then we get the index of the selected option with sel.selectedIndex.
Next we use that with sel.options to get the option that’s selected.
And then get the text of the option with the text property.
Conclusion
To get JavaScript select box’s selected text, we can use the select element’s options and selectedIndex properties.