Categories
JavaScript Answers

How to get JavaScript select box’s selected text?

Spread the love

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.

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 *