我有
<select id="x">
<option value="5">hi</option>
<option value="7">hi 2</option>
</select>
我想要一个javascript函数,它允许我选择并显示<option>
作为id的默认值。换句话说,我想做一个setOption(5)
和值为“5”的<option>
作为默认值显示在组合框中。
那可能吗?
如果可以的话,用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');
如果它返回false
,则无法找到该值:)
使用Javascript:
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
如果您使用的是jQuery(1.6或更高版本)
$('#x option[value="5"]').prop('selected', true)
如果有人在寻找jquery解决方案,请使用val()
函数。
$("#select").val(valueToBeSelected);
在Javascript中,
document.getElementById("select").value = valueToBeSelected;
您甚至不需要javascript参与,只需使用selected
属性:
<select id="x">
<option value="5" selected>hi</option>
<option value="7">hi 2</option>
</select>