javascript 如何使用javascript设置下拉列表的选定索引

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

How to set the selected index of a dropdown using javascript

javascriptasp-classicvbscript

提问by jain ruchi

How can I set the selected value of a dropdown using javascript?

如何使用javascript设置下拉列表的选定值?

This is my HTML:

这是我的 HTML:

<select id="strPlan" name="strPlan" class="formInput">
    <option value="0">Select a Plan</option>
</select>

I am using javascript to add values. Can anyone tell me how to call a function to select a value?

我正在使用 javascript 添加值。谁能告诉我如何调用函数来选择一个值?

回答by Some Guy

How can I set the selected value of a dropdown using javascript?

如何使用javascript设置下拉列表的选定值?

So, you want to change the value of the option that is currently selected. Is that correct?

因此,您要更改当前选择的选项的值。那是对的吗?

function setValueOfSelected(select, valueToSetTo){
    select.options[select.selectedIndex].value = valueToSetTo;
}

And call it like this:

并这样称呼它:

setValueOfSelected(document.getElementById('strPlan'), 'selected');

Demo

演示



In case you meant that you want to select an option based on its value, use this:

如果您的意思是要根据其值选择一个选项,请使用以下命令:

Declare this function:

声明这个函数:

function setOptionByValue(select, value){
    var options = select.options;
    for(var i = 0, len = options.length; i < len; i++){
        if(options[i].value === value){
            select.selectedIndex = i;
            return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
        }
    }
    return false; //Just to let you know it didn't find any option with that value.
}

Now call that to set the option by value, like this, with the first parameter being the select element and the second being the value:

现在调用它来按值设置选项,像这样,第一个参数是选择元素,第二个参数是值:

setOptionByValue(document.getElementById('strPlan'), '1');

Demo

演示

回答by Peter

Something like this could work, I believe:

我相信这样的事情可以工作:

function setDropDownList(elementRef, valueToSetTo)
{
    var isFound = false;

    for (var i = 0; i < elementRef.options.length; i++) {
        if (elementRef.options[i].value == valueToSetTo) {
            elementRef.options[i].selected = true;
            isFound = true;
        }
    }

    if ( isFound == false )
        elementRef.options[0].selected = true;
}

Found it here. Just Google for something like 'set selected value dropdown javascript' and you'll get many possible solutions.

在这里找到。只需谷歌搜索“设置选定值下拉javascript”之类的内容,您就会得到许多可能的解决方案。