jQuery – 在选择框中选择选项
可能重复:
jQuery / Programmatically在Select Box中选择一个选项
我想知道,是否可以直接从jQuery中选择selectbox / combobox中的选项。 例如,我想在select中选择值为5的选项,其值为1到10。
我能想到的唯一解决方案是删除所有选项并使用正确的选择值重新创建它们,但这有点不高效。
只需像处理任何其他输入元素一样处理选择框:
$("#MySelectBox").val("5");
您可以通过在标记中添加
selected
属性来完成此操作。
$(document).ready(function () { $('#btn2').click(function(){ $('#sel1 option[value=2]').attr('selected','selected'); }); $('#btn3').click(function(){ $('#sel1 option[value=3]').attr('selected','selected'); }); $('#btn5').click(function(){ $('#sel1 option[value=5]').attr('selected','selected'); }); });
当然可以
只需使用此代码选择选项5:
$("#ComboBox").val(5);
例
您所要做的就是将selected
属性设置为true
或selected
。
var arrayOfOptions = $('#mySelect option') //will return an array of options in the order they are found
只需迭代它们,例如:
for(var i=0; i
如果我理解正确,您需要选择值为5的选项并将其标记为已选中。 如果是这样,那应该是这样的:
$("#selectBox[value='5']").attr('selected', 'selected');
这应该也有效:
$("#selectBox").attr('value', 5).attr('selected', 'selected');