Javascript: Select option based on its contents
Basically this, but in pure javascript:
How to get 'value' of select tag based on content of select tag, using NokogiriI 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 indivi开发者_C百科dual one - not economical)
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;
}
}
Now that querySelector is available in most browsers you can use:
document.querySelector('select').selectedIndex =
document.querySelector('option[value=4783]').index;
Just 10 years late, but let's look at a new age solution.
If you are working in ES6+ here is a simple "one liner" to do the trick.
If you require broad compatibility, use a transpiler or another solution.
let $select = document.querySelector('select[name="countries"]');
let compareValue = 'Argentina';
$select.value = [...$select.options].filter(option => {
return option.innerText === compareValue;
})[0].value;
The true one-liner expression:
$select.value = [...$select.options].filter(option => option.innerText === compareValue)[0].value;
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).
精彩评论