Javascript jQuery - 在选择框中选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7399640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - select option in select box
提问by Eduard Luca
Possible Duplicate:
jQuery / Programmatically Select an Option in Select Box
I was wondering, is it possible to select an option from a selectbox/combobox directly from jQuery. For example I want to select the option with the value 5 in a select with values from 1 to 10.
我想知道,是否可以直接从 jQuery 的选择框/组合框中选择一个选项。例如,我想在值从 1 到 10 的选择中选择值为 5 的选项。
The only solution I can think of is to remove all options and recreate them with the right selected value, but that's a bit unefficient.
我能想到的唯一解决方案是删除所有选项并使用正确的选定值重新创建它们,但这有点低效。
回答by njr101
Just treat the select box as you would any other input element:
只需像对待任何其他输入元素一样对待选择框:
$("#MySelectBox").val("5");
回答by Mansoor Gee
You can do this by adding the selected
attribute in <option>
tag.
您可以通过selected
在<option>
标签中添加属性来做到这一点。
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<select id="sel1">
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
<option value='4'>Option 4</option>
<option value='5'>Option 5</option>
<option value='6'>Option 6</option>
<option value='7'>Option 7</option>
<option value='8'>Option 8</option>
<option value='9'>Option 9</option>
</select>
<input id="btn2" type=button value='Select 2' />
<input id="btn3" type=button value='Select 3' />
<input id="btn5" type=button value='Select 5' />
回答by JSantos
回答by Ali
All you have to do is go around setting the attribute selected
to true
or selected
.
您所要做的就是将属性设置selected
为true
or selected
。
var arrayOfOptions = $('#mySelect option') //will return an array of options in the order they are found
Just iterate over them, something like:
只需迭代它们,例如:
for(var i=0; i<arrayOfOptions.length; i++) {
var opt = arrayOfOptions[i];
//feel free to check the index of i here if you want to set
//a particular index to selected or a range.
//similarly the range can be passed in as a function parameter.
$(opt).attr('selected','selected');
}
回答by Allen Liu
If I understand you correctly, you want to select the option with value=5 and mark it selected. If so, this should be it:
如果我理解正确,您想选择 value=5 的选项并将其标记为选中。如果是这样,这应该是:
$("#selectBox[value='5']").attr('selected', 'selected');
This should also work:
这也应该有效:
$("#selectBox").attr('value', 5).attr('selected', 'selected');