最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript: Select option based on its contents - Stack Overflow

programmeradmin1浏览0评论

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)

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)

Share Improve this question edited May 23, 2017 at 12:18 CommunityBot 11 silver badge asked May 30, 2010 at 0:53 Zac AltmanZac Altman 1,2134 gold badges25 silver badges37 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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 patibility, use a transpiler or another solution.

let $select = document.querySelector('select[name="countries"]');
let pareValue = 'Argentina';

$select.value = [...$select.options].filter(option => {
    return option.innerText === pareValue;
})[0].value;

The true one-liner expression:

$select.value = [...$select.options].filter(option => option.innerText === pareValue)[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).

发布评论

评论列表(0)

  1. 暂无评论