按值选择<select>项

Ron*_*ero 12 html javascript option

我有

<select id="x">
    <option value="5">hi</option>
    <option value="7">hi 2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我想要一个javascript函数,它允许我选择并显示<option>id作为默认值.换句话说,我想做一个setOption(5)<option>值"5"作为默认值显示在组合框中.

那可能吗?

ale*_*lex 18

如果可以的话,用ES6 ......

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

...除此以外...

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');
Run Code Online (Sandbox Code Playgroud)

看见!

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

  • @Ronan Dejhero它将访问每次迭代的长度属性:) (3认同)

Aar*_*rvy 6

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

$("#select").val(valueToBeSelected);
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 中,

document.getElementById("select").value = valueToBeSelected; 
Run Code Online (Sandbox Code Playgroud)