按值选择项目

问题描述 投票:11回答:5

我有

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

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

那可能吗?

javascript html option
5个回答
17
投票

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

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

...除此以外...

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!

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


3
投票

使用Javascript:

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

2
投票

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

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

2
投票

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

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

在Javascript中,

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

-2
投票

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

<select id="x">
  <option value="5" selected>hi</option>
  <option value="7">hi 2</option>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.