如果选择了其他选项,我正在尝试弄清楚如何取消选择多选框的选定项目。在下面的场景中,我只想在选择任何其他选项(或所有其他选项)时取消选择“admin”(默认值)选项。
简单地说:默认选择管理员,如果用户选择“用户”或“编辑”或两者,管理员应取消选择。
目前,它没有取消选择。
$('#groups').on('change', function () {
var selected = $('#groups').find('option:selected').val();
console.log('selected: ' + selected);
// if anything other than admin is selected deselect admin
if (selected !== 'admin') {
$('#admin').prop('selected', false);
}
});
HTML:
<div class="col-md-3">
<select class="form-control" id="groups" multiple>
<option value="admin" selected="selected" id="admin">Admin Only</option>
<option value="user">User</option>
<option value="editor">Editor</option>
</select>
</div>
答案 0 :(得分:1)
好吧,您可以遍历undefined
,当值select options
的{{1}}到来时,您可以通过将selected属性设置为false来取消选中它。
select option
&#13;
"admin"
&#13;
答案 1 :(得分:1)
我明白了:
groups.on('change', function () {
// if anything other than admin is selected deselect admin
var selected = groups.find('option:selected');
console.log('selected: ' + selected.val());
if (selected.val() == 'admin' && selected.length == 1) {
$('#admin').prop('selected', true);
} else {
$('#admin').prop('selected', false);
}
});
groups
只是选择器的别名。
答案 2 :(得分:1)
$('#groups').on('change', function () {
var values = $(this).val();
var new_values = [];
if ((values.includes('user')) || (values.includes('editor'))){
for(var i=0; i<values.length; i++){
if (values[i] !== 'admin'){
new_values.push(values[i])
}
}
$(this).val(new_values);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<select class="form-control" id="groups" multiple>
<option value="admin" selected="selected" id="admin">Admin Only</option>
<option value="user">User</option>
<option value="editor">Editor</option>
</select>
</div>
答案 3 :(得分:0)
使用我尝试的jQuery 2.2.4版本取消选择下面包含的选项。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-3">
<select class="form-control" id="groups" multiple="multiple">
<option value="admin" selected="selected" id="admin">Admin Only</option>
<option value="user">User</option>
<option value="editor">Editor</option>
</select>
</div>
</body>
</html>
<script>
$('#groups').on('change', function () {
var selected = $('#groups').find('option:selected').val();
console.log('selected: ' + selected);
if (selected == 'admin') {
$("#groups > option:selected").attr("selected",false);
$('#groups > option[value="admin"]').prop('selected', true);
}
});
</script>