按值选择<选择>项目</select>

时间:2010-12-01 12:03:38

标签: javascript html option

我有

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

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

这可能吗?

6 个答案:

答案 0 :(得分: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,则找不到该值:)

答案 1 :(得分:4)

如果有人在寻找jquery解决方案,请使用Dim item As Variant For Each item In Split(SheetNames, ",") SheetNameCollection.Add item Next 函数。

val()

在Javascript中,

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

答案 2 :(得分:3)

使用Javascript:

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

答案 3 :(得分:2)

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

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

答案 4 :(得分:0)

所以我遇到了这个问题,以为我会提供一些解决方案。

单个选择的最简单方法是设置选择的值:

var mySelect = document.getElementById( 'my-select-id' );
mySelect.value = 7;

您也可以按照相同的方式通过值获得所选选项:

console.log( mySelect.value );

我一直在寻找一种更好的方法来设置多选(<select multiple>...</select>)的值,但事实证明-似乎您必须遍历选项,并以某种{ {1}}循环:

for

然后像这样使用它:

function setMultiSelectValues( select, values ) {
    for (var i = 0; i < select.options.length; i++) {
        var option = select.options[i];
        if ( values.includes( option.value ) ) {
            option.selected = true;
        }
    }
}

演示https://codepen.io/rmorse/pen/QWNymdb

答案 5 :(得分:-2)

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

<select id="x">
  <option value="5" selected>hi</option>
  <option value="7">hi 2</option>
</select>
相关问题