多选列表:
<select id="fruits" name="fruits" multiple="multiple">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
脚本代码:
var groups=["Apple","Orange"]; //Only Apple and orange values should be selected
$('#fruits').val(groups);
答案 0 :(得分:3)
您应该将value
设置为正确。截至目前,您传递的文字不是值。
var groups=[1,3];
var groups=[1,3];
$('#fruits').val(groups);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fruits" name="fruits" multiple="multiple">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
&#13;
但是您仍然希望使用["Apple","Orange"];
,.filter()
方法可以与.prop()
var groups = ["Apple", "Orange"];
$('#fruits option').filter(function() {
return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fruits" name="fruits" multiple="multiple">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
&#13;
答案 1 :(得分:1)
希望这会对你有所帮助。
var groups = ["Apple", "Orange"];
$('#fruits').val(groups);
$('select[name*="fruits"]').find('option').each(function() {
var str = $(this).text()
if (!contains(groups, str)) {
$(this).prop('disabled', 'disabled');
}
});
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fruits" name="fruits" multiple="multiple">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
&#13;