我的 HTML 中有一个多选列表。如果选择值 296,则必须取消选择所有其他选项。
这是我正在使用的代码,因此当我想选择多个选项时不必使用 CTRL:
$("#select").mousedown(function(e) {
e.preventDefault();
var select = this;
var scroll = select.scrollTop;
if (select.value == 296) {
//unselect all the other options
}
e.target.selected = !e.target.selected;
setTimeout(function() {
select.scrollTop = scroll;
}, 0);
$(select).focus();
}).mousemove(function(e) {
e.preventDefault()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">
<option value="296">Primairadres </option>
<option value="297">Bezoekadres </option>
<option value="298">Factuuradres </option>
<option value="299">Postadres </option>
</select>
我似乎不知道如何在选择值 296 时取消选择所有其他选项
最佳答案
下面的内容似乎实现了您上面所说的。如果已经选择了 296,它也会阻止您选择选项。
const unselect = '296'
$('#select').change(function() {
const $el = $(this)
console.log($el.val())
if ($el.val().indexOf(unselect) !== -1) {
$el.children('option').each(function() {
$opt = $(this)
if ($opt.val() !== unselect) {
$opt.prop('selected', false)
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" name="adrestype_id" class="form-control" required="required" multiple="multiple">
<option value="296">Primairadres </option>
<option value="297">Bezoekadres </option>
<option value="298">Factuuradres </option>
<option value="299">Postadres </option>
</select>
关于javascript - 多选,当选择某一选项时,取消选择其他选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42925329/