如何使用显示文本设置select元素的selectedIndex?

dpp*_*dpp 41 javascript selectedindex

如何使用显示文本作为参考设置select元素的selectedIndex?

例:

<input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

<script type="text/javascript">
    function SelectAnimal()
    {
        //Set selected option of Animals based on AnimalToFind value...
    }
 </script>
Run Code Online (Sandbox Code Playgroud)

没有循环,有没有其他方法可以做到这一点?你知道,我在想一个内置的JavaScript代码.另外,我不使用jQuery ...

Jac*_*kin 58

试试这个:

function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @domanokz你在那里看到任何`jQuery`吗?因为我没有. (17认同)
  • @JacobRelkin我知道这是一篇旧文章,但我觉得我需要指出`sel.options.length`不会计算任何东西,因为它不是一个函数。您正在访问“sel.options”对象中包含的变量。`j = sel.options.length` 不是必需的。 (2认同)

Ibu*_*Ibu 9

<script type="text/javascript">
     function SelectAnimal(){
         //Set selected option of Animals based on AnimalToFind value...
         var animalTofind = document.getElementById('AnimalToFind');
         var selection = document.getElementById('Animals');

        // select element
        for(var i=0;i<selection.options.length;i++){
            if (selection.options[i].innerHTML == animalTofind.value) {
                selection.selectedIndex = i;
                break;
            }
        }
     }
</script>
Run Code Online (Sandbox Code Playgroud)

设置select标签的selectedIndex属性将选择正确的项目.最好不要比较两个值(选项innerHTML && animal value),你可以使用indexOf()方法或正则表达式来选择正确的选项,尽管空格或空格的存在

selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
Run Code Online (Sandbox Code Playgroud)

或使用 .match(/regular expression/)