Categories
JavaScript Answers

How to set dropdown selected item based on option text with JavaScript?

Spread the love

To set dropdown selected item based on option text with JavaScript, we set the selectedIndex property of the select drop down.

For instance, we write

<select id="myDropDown">
  <option value="0">Google</option>
  <option value="1">Bing</option>
  <option value="2">Yahoo</option>
</select>

to add the drop down.

Then we write

const textToFind = "Bing";
const dd = document.getElementById("myDropDown");
dd.selectedIndex = [...dd.options].findIndex(
  (option) => option.text === textToFind
);

to get the select drop down with getElementById.

Then we find the element with the options we want to set with findIndex.

We get the node list of option elements with dd.options and spread the entries into an array before using findIndex.

option.text has the option text.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.