问题
Basically this, but in pure javascript:
How to get 'value' of select tag based on content of select tag, using Nokogiri
I have a select list with a lot of countries/states, and I want to be able to select one based on what is between the <option>
tags.
<option value="4783">Argentina</option>
(I know I could use the value, but each one is a random mesh of numbers, so I would have to collect each individual one - not economical)
回答1:
It is a bit painful, but in pure JavaScript:
for(var i=0,sL=mySelObj.length;i<sL;i++){
if(mySelObj.options[i].text == myValue){
mySelObj.selectedIndex = i;
break;
}
}
回答2:
Now that querySelector is available in most browsers you can use:
document.querySelector('select').selectedIndex =
document.querySelector('option[value=4783]').index;
回答3:
The textContent
property lets you see what's inside the tag. Off my head and without testing, that should work:
function selectByDisplayValue(selectTag, displayValue)
{
var options = selectTag.getElementsByTagName('option');
for(var i = 0; i < options.length; i++)
if(options[i].textContent == displayValue)
{
options[i].selected = true;
break;
}
}
Where selectTag
is the DOM object of your <select>
tag, and displayValue
is the display value of the option you want to select (for your example, "Argentina" it would be).
来源:https://stackoverflow.com/questions/2937134/javascript-select-option-based-on-its-contents