tags:

views:

17

answers:

2

say I have a dropdown list like this:

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

and I want to set the selected value based on the option text, not the value with javascript. How can I go about doing this? For example, with c# I can do something like the example below and the the option with "Google" would be selected.

ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
   mt.Selected = true;
}

Thanks in advance for any help!

+1  A: 
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;
        break;
    }
}
Gabriel McAdams
worked like a charm! many thanks!
dkirk
A: 

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

janechii
oops... yea like what Gabriel says...
janechii