Categories
JavaScript Answers

How to get the text from a dropdown box with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *