我是编码的新手,正试图限制用户最多选择两个颜色选项。我无法弄清楚代码中哪里出了问题。
<label class="container" for="red">Red
<input class="single-check" type="checkbox" id="red">
<span class="checkmark red"></span>
</label>
<label class="container" for="blue">Blue
<input class="single-check" type="checkbox" id="blue">
<span class="checkmark blue"></span>
</label>
<label class="container" for="green">Green
<input class="single-check" type="checkbox" id="green">
<span class="checkmark green"></span>
</label>
<label class="container" for="yellow">Yellow
<input class="single-check" type="checkbox" id="yellow">
<span class="checkmark yellow"></span>
</label>
<script type="text/javascript">
var limit = 2;
$('input.single-check').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
</script>
答案 0 :(得分:0)
问题是因为复选框不是兄弟姐妹。您需要更改逻辑以选择所有复选框,然后计算已被选中的复选框的数量,您可以使用filter()
进行操作,如下所示:
var limit = 2;
var $checkboxes = $('input[type=checkbox]').on('change', function(evt) {
if ($checkboxes.filter(':checked').length > limit) {
this.checked = false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="container" for="red">Red
<input class="single-check" type="checkbox" id="red">
<span class="checkmark red"></span>
</label>
<label class="container" for="blue">Blue
<input class="single-check" type="checkbox" id="blue">
<span class="checkmark blue"></span>
</label>
<label class="container" for="green">Green
<input class="single-check" type="checkbox" id="green">
<span class="checkmark green"></span>
</label>
<label class="container" for="yellow">Yellow
<input class="single-check" type="checkbox" id="yellow">
<span class="checkmark yellow"></span>
</label>
答案 1 :(得分:0)
您的问题是您正在使用.siblings
来引用其他输入,但是它们不是同级的,因为它们都嵌套在标签内。
您不需要相对于所选项目找到它们,只需像这样直接找到它们:
$('input[type=checkbox]').on('change', function() {
if($('input[type=checkbox]:checked').length > limit) {
this.checked = false;
}
});
(此外,如果您最多选择2个,则您的测试应为> limit
,而不是>= limit
)