Select an option item from the drop-down list by its text value

Given an HTML form element, for example:

<select id='mydropdown'> <option value='foo'>Spam</option> <option value='bar'>Eggs</option> </select> 

I know that I can choose the first option with

 document.getElementById("mydropdown").value='foo' 

However, let's say I have a variable with the value "Spam"; Can I select a dropdown item by its text, and not by its value?

+6
source share
4 answers
 var desiredValue = "eggs" var el = document.getElementById("mydropdown"); for(var i=0; i<el.options.length; i++) { if ( el.options[i].text == desiredValue ) { el.selectedIndex = i; break; } } 
+25
source

I would use selectIndex or a loop to select an option in the text, the code below does not work.

 document.getElementById("mydropdown").text = 'Eggs'; 
+1
source

If you want to get an option by its inner text, and not by value, you can do this:

 function go(){ var dropdown = document.getElementById('mydropdown'); var textSelected = 'Spam'; for(var i=0, max=dropdown.children.length; i<max; i++) { if(textSelected == dropdown.children[i].innerHTML){ alert(textSelected); return; } } } 
0
source

Old IE does not treat select parameters as child nodes, but all browsers implement the text property of the collection of selection options.

 function selectbytext(sel, txt){ if(typeof sel== 'string'){ sel= document.getELementById(sel) || document.getELementsByName(sel)[0]; } var opts= sel.options; for(var i= 0, L= opts.length; i<L; i++){ if(opts[i].text== txt){ sel.selectedIndex= i; break; } } return i; } 
0
source

Source: https://habr.com/ru/post/885742/


All Articles