javascript 从下拉列表中动态选择值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9976042/
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-10-26 08:23:53  来源:igfitidea点击:

dynamically select value from drop down list

javascript

提问by Kim

I have the following drop down list:

我有以下下拉列表:

<select name="selSS1" id="select_value">
    <option value="val0">sea zero</option>
    <option value="val1">sea one</option>
    <option value="val2">sea two</option>
    <option value="val3">sea three</option>
    <option value="val4">sea four</option>
</select>

I would like to dynamically select a value from that list using javascript:

我想使用 javascript 从该列表中动态选择一个值:

I tried:

我试过:

document.getElementById('select_value').selected ="val3";

But the above code does not seem to work. Any help is most appreciated.

但是上面的代码似乎不起作用。非常感谢任何帮助。

回答by AmGates

Use the following line:

使用以下行:

 document.getElementById('select_value').value ="val3";

or 

    document.getElementById('select_value').selectedIndex = 3;

Hope this solves ur problem.

希望这能解决你的问题。

回答by Pratik Bhatt

$('#select_value').val('val0');

回答by Bogdan Emil Mariesan

With plain JavaScript:

使用纯 JavaScript:

var element = document.getElementById("select_value");
var selectedValue = element.options[element.selectedIndex].value;

回答by Th0rndike

try:

尝试:

var mySelect = document.getElementById('select_value');
mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected');

where index stands for the position of the option you want to select.

其中 index 代表您要选择的选项的位置。

回答by Rafael Marques

Try it this way:

试试这个方法:

document.getElementById('select_value').option[3].selected;

document.getElementById('select_value').option[3].selected;

回答by Kunal Vashist

THis will select val 3

这将选择 val 3

document.getElementById('select_value').selectedIndex=3;

回答by Javier Cobos

If you want to set the selected one by the value, try this function. By declaring a function you will be able to use this functionality with any select :).

如果您想通过值设置选定的一个,请尝试此功能。通过声明一个函数,您将能够将此功能与任何选择一起使用 :)。

// Simplest version

// 最简单的版本

function setSelected(select_id,value){

    document.getElementById(select_id).value = value;

}

// Or, complex version

// 或者,复杂版本

function setSelected(select_id,value){

    var mySelect = document.getElementById(select_id);
    var options = mySelect.options;
    var key;
    for(key in options){

        if(options[key].value===value){
            options[key].setAttribute("selected","");
        }
        else
            options[key].removeAttribute("selected");
    }
}

in your case:

在你的情况下:

setSelected("select_value","val3");