46

表示テキストを参照として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>

ループなしでこれを行う他の方法はありますか? ご存知のように、組み込みの JavaScript コードか何かを考えています。また、私はjQueryを使用していません...

4

7 に答える 7

63

これを試して:

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;
        }
    }
}
于 2011-06-02T04:39:30.933 に答える
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>

select タグの selectedIndex プロパティを設定すると、正しいアイテムが選択されます。2 つの値 (options innerHTML && animal value) を比較する代わりに、indexOf() メソッドまたは正規表現を使用して、大文字と小文字の区別やスペースの有無にかかわらず正しいオプションを選択することをお勧めします。

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

または使用して.match(/regular expression/)

于 2011-06-02T04:39:47.377 に答える
3

これを試して:

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;
      }     
    }
}
于 2011-06-02T04:38:25.053 に答える