Categories
JavaScript Answers

How to Set a Dropdown’s Selected Item Based on Option Text with JavaScript?

Spread the love

Sometimes, we want to set a dropdown’s selected item based on option text with JavaScript.

In this article, we’ll look at how to set a dropdown’s selected item based on option text with JavaScript.

Set a Dropdown’s Selected Item Based on Option Text with JavaScript

To set a dropdown’s selected item based on option text with JavaScript, we search for the index of the option text in the dropdown.

Then we can set the selectedIndex of the select drop down to the returned index.

For instance, we write:

<select>
  <option value='yahoo'>Yahoo</option>
  <option value='bing'>Bing</option>
  <option value='google'>Google</option>
</select>

to create a drop-down with some options.

Then we write:

const textToFind = 'Google';
const dd = document.querySelector('select');
dd.selectedIndex = [...dd.options].findIndex(option => option.text === textToFind);

to set textToFind to the text we want to find.

Then we select the drop-down with document.querySelector .

Next, we spread the dd.options which has the option elements in the select drop down into an array.

Then we call findIndex to find the index of the option element that has the textToFind as the text, which is the content between the opening and closing tags.

Finally, we set the returned index as the value of dd.selectedIndex .

Therefore, we should see 'Google' selected as a result.

Conclusion

To set a dropdown’s selected item based on option text with JavaScript, we search for the index of the option text in the dropdown.

Then we can set the selectedIndex of the select drop down to the returned index.

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 *