Javascript 使用javascript选择下拉菜单选项

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

Select dropdown menu option with javascript

javascripthtmldrop-down-menu

提问by shinjuo

I have a dropdown menu and I cannot figure out how to make a javascript function select a drop down menu option. I have tested the output of the variables and they are all correct, but it still will not select the option when clicked. Here is the function and drop down menu.

我有一个下拉菜单,但我不知道如何让 javascript 函数选择一个下拉菜单选项。我已经测试了变量的输出,它们都是正确的,但是单击时仍然不会选择该选项。这是功能和下拉菜单。

Function

功能

function formFill(a, b, c){
        theform.from.value = a;
        theform.to.value = b;
        for(var i = 0;i < document.getElementById("stateSelect").length;i++){
            if(document.getElementById("stateSelect").options[i].value == c ){
                document.getElementById("stateSelect").selected = true;
            }
        }
    }

Menu item

菜单项

<select id="stateSelect" name="stateSelect">
    <option value="none">(None)</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>

回答by David Hancock

Change the line that reads:

更改读取的行:

document.getElementById("stateSelect").selected = true;

document.getElementById("stateSelect").selected = true;

to:

到:

document.getElementById("stateSelect").selectedIndex = i;

document.getElementById("stateSelect").selectedIndex = i;

回答by Anatoly Mironov

Alt. you can set selected to the actual option: select.options[i].selected = true;

替代。您可以将 selected 设置为实际选项:select.options[i].selected = true;

...
        var select = document.getElementById("stateSelect");
        for(var i = 0;i < select.options.length;i++){
            if(select.options[i].value == c ){
                select.options[i].selected = true;
            }
        }
...