Sometimes, we want to get the text from a dropdown box with JavaScript.
in this article, we’ll look at how to get the text from a dropdown box with JavaScript.
How to get the text from a dropdown box with JavaScript?
To get the text from a dropdown box with JavaScript, we can use the options
and selectedIndex
properties.
For instance, we write
const skillsSelect = document.getElementById("newSkill");
const selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
to select the select element with getElementById
.
Then we use skillsSelect.options
to get all the options in an iterable object.
We use skillsSelect.selectedIndex
to get the index of the selected option and use that to get the selected option with skillsSelect.options[skillsSelect.selectedIndex]
.
Then we use the text
property to get the text of the dropdown.
Conclusion
To get the text from a dropdown box with JavaScript, we can use the options
and selectedIndex
properties.