javascript 按值选择 <select> 项

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

select <select> item by value

javascripthtmloption

提问by Rami Dabain

i have

我有

<select id="x">
    <option value="5">hi</option>
    <option value="7">hi 2</option>
</select>

I want a javascript function that enables me to select and display the <option>as default one by id. In other words, I want to do a setOption(5)and the <option>with the value "5" to be displayed in the combobox as a default .

我想要一个 javascript 函数,它使我能够<option>按 id选择和显示默认值。换句话说,我想做一个setOption(5)<option>值“5”作为默认值显示在组合框中。

Is that possible?

那可能吗?

回答by alex

If you can, with ES6...

如果可以,使用 ES6 ...

function setOption(selectElement, value) {
    return [...selectElement.options].some((option, index) => {
        if (option.value == value) {
            selectElement.selectedIndex = index;
            return true;
        }
    });
}

...otherwise...

...否则...

function setOption(selectElement, value) {
    var options = selectElement.options;
    for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
        if (options[i].value == value) {
            selectElement.selectedIndex = i;
            return true;
        }
    }
    return false;
}

setOption(document.getElementById('my-select'), 'b');

See it!

看见!

If it returns false, then the value could not be found :)

如果它返回false,则找不到该值:)

回答by Dasun

If you are using jQuery (1.6 or greater)

如果您使用 jQuery(1.6 或更高版本)

$('#x option[value="5"]').prop('selected', true)

回答by Dasun

Using Javascript:

使用 JavaScript:

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

回答by Aarvy

If someone looking for jquery solution, use the val()function.

如果有人在寻找 jquery 解决方案,请使用该val()功能。

$("#select").val(valueToBeSelected);

In Javascript,

在 JavaScript 中,

document.getElementById("select").value = valueToBeSelected; 

回答by fifigyuri

You should not need even javascript to get involved, use simply the selectedattribute:

您甚至不需要 javascript 参与,只需使用selected属性:

<select id="x">
  <option value="5" selected>hi</option>
  <option value="7">hi 2</option>
</select>