Javascript: Select option based on its contents

ぃ、小莉子 提交于 2019-12-11 14:07:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!