javascript select option based on text 1

javascript select option based on text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;

Here is what the above code is Doing:
1. It's getting the dropdown element by its ID.
2. It's looping through all the options in the dropdown.
3. It's comparing the text of each option to the text we want to find.
4. If the text matches, it sets the selectedIndex of the dropdown to the index of the option we want.
5. It breaks out of the loop.

Similar Posts