Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: set dropdown selected item based on option text

Tags:

javascript

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!

like image 315
user1017477 Avatar asked Oct 21 '10 15:10

user1017477


People also ask

How to change select option text in JavaScript?

getElementById('stuff'). options[0]. innerHTML = "Water"; ... which get one select but on Id and not name rather than what was given: document. getElementsByName('stuff')[0].

How do you bind a selected item in a drop-down list to a text box and edit it?

You can bind a selected value from the drop-down list using the ngModel and edit it inside the text box or numeric input box. The selected item text and value can be got using the change event of the drop-down list through the args. itemData.

How do I set the text value of a selected option jQuery?

4.2) to set the 'selected' attribute of a select list based on its 'text' description rather than its 'value': $("#my-Select option[text=" + myText +"]"). attr("selected","selected") ; This code worked fine, until I noticed one select list on which it failed, depending on the text that was being matched.


1 Answers

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;     } } 
like image 133
Gabriel McAdams Avatar answered Oct 20 '22 15:10

Gabriel McAdams