Categories
JavaScript Answers

How to get selected option text with JavaScript?

Spread the love

To get selected option text with JavaScript, we can use the selectedIndex property.

For instance, we write

<select id="box1" onChange="onChange(this);">
  <option value="98">dog</option>
  <option value="7122">cat</option>
  <option value="142">bird</option>
</select>

to add a select drop down.

We set the onchange attribute to call onChange with the select element.

Then we write

function onChange(sel) {
  console.log(sel.options[sel.selectedIndex].text);
}

to define the onChange function.

We get the selected option with sel.options[sel.selectedIndex].

And we get the option’s text with the text property.

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 *