Javascript 如何使用显示文本设置选择元素的 selectedIndex?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6210390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:46:57  来源:igfitidea点击:

How to set selectedIndex of select element using display text?

javascriptselectedindex

提问by dpp

How to set selectedIndex of select element using display text as reference?

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

Example:

例子:

<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>

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

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

回答by Jacob Relkin

Try this:

尝试这个:

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;
        }
    }
}

回答by Ibu

<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>

setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces

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

selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;

or using .match(/regular expression/)

或使用 .match(/regular expression/)

回答by tradyblix

Try this:

尝试这个:

function SelectAnimal()
{
    var animals = document.getElementById('Animals');
    var animalsToFind = document.getElementById('AnimalToFind');
    // get the options length
    var len = animals.options.length;
    for(i = 0; i < len; i++)
    {
      // check the current option's text if it's the same with the input box
      if (animals.options[i].innerHTML == animalsToFind.value)
      {
         animals.selectedIndex = i;
         break;
      }     
    }
}

回答by Brandon

If you want this without loops or jquery you could use the following This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.

如果你想要这个没有循环或 jquery,你可以使用以下这是直接的 JavaScript。这适用于当前的网络浏览器。鉴于这个问题的年龄,我不确定这是否会在 2011 年有效。请注意,使用 css 样式选择器非常强大,可以帮助缩短大量代码。

// Please note that querySelectorAll will return a match for 
// for the term...if there is more than one then you will 
// have to loop through the returned object
var selectAnimal = function() {
  var animals = document.getElementById('animal');
  if (animals) {
    var x = animals.querySelectorAll('option[value="frog"]');
    if (x.length === 1) {
      console.log(x[0].index);
      animals.selectedIndex = x[0].index;
    }
  }
}
<html>

<head>
  <title>Test without loop or jquery</title>
</head>

<body>
  <label>Animal to select
  <select id='animal'>
    <option value='nothing'></option>
    <option value='dog'>dog</option>
    <option value='cat'>cat</option>
    <option value='mouse'>mouse</option>
    <option value='rat'>rat</option>
    <option value='frog'>frog</option>
    <option value='horse'>horse</option>
  </select>
  </label>
  <button onclick="selectAnimal()">Click to select animal</button>

</body>

</html>

document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); in the index object you can now do the following: x[0].index

document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); 在索引对象中,您现在可以执行以下操作:x[0].index

回答by ssingh

You can set the index by this code :

您可以通过以下代码设置索引:

sel.selectedIndex = 0;

but remember a caution in this practice, You would not be able to call the server side onclickmethod if you select the previous value selected in the drop down..

但请记住在此实践中的一个警告,onclick如果您选择在下拉列表中选择的先前值,您将无法调用服务器端方法。

回答by Jose

Add name attribute to your option:

将 name 属性添加到您的选项:

<option value="0" name="Chicken">Chicken</option>

With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

有了它,您可以使用 HTMLOptionsCollection.namedItem("Chicken").value 来设置 select 元素的值。

回答by Jose

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

您可以使用 HTMLOptionsCollection.namedItem() 这意味着您必须定义您的选择选项以具有名称属性并具有显示文本的值。例如加利福尼亚