我试图弄清楚如果选择了另一个选项,如何取消选择多选框中的选定项目。在以下场景中,如果选择了任何其他选项(或所有其他选项),我只想取消选择“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>
最佳答案
我明白了:
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
只是选择器的别名。
关于jquery - 在一定条件下取消多选框的选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205994/