Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 145707  / 14 Years ago, thu, october 21, 2010, 12:00:00

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;
}

More From » javascript

 Answers
12
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;
}
}

[#95224] Wednesday, October 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ashly

Total Points: 601
Total Questions: 95
Total Answers: 88

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
;