【发布时间】:2017-12-10 01:49:24
【问题描述】:
我有一个单选按钮和几个复选框。我基本上想在选择 Non-Exclusive 时禁用复选框,然后在选择 Package 1 时将复选框限制为 2。
这是我的 html 代码:
<label>
<input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
<input type="radio" value="package1" id="package1" name="packages"> Package 1
</label>
<label>
<input type="radio" value="package2" id="package2" name="packages"> Package 2
</label>
<br />
<label><h2>Rice </h2></label>
<br />
<a style="color: darkred;">2 Choices</a>
<br />
<div class="checkboxfood">
<label>
<input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
</label>
<label>
<input type="checkbox" class="food" value=""> Buttered Rice
</label>
<label>
<input type="checkbox" class="food" value=""> Garlic Rice
</label>
<label>
<input type="checkbox" class="food" value=""> Kimchi Rice
</label>
<label>
<input type="checkbox" class="food" value=""> Adobo Rice
</label>
<label>
<input type="checkbox" class="food" value=""> Yang Chow Rice
</label>
<br />
<label>
<input type="checkbox" class="food" value=""> Shanghai Rice
</label>
<label>
<input type="checkbox" class="food" value=""> Bagoong Rice
</label>
</div>
我试过这个javascript:
$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);
});
$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});
$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});
它启用复选框,但不会限制它。此外,如果我按回 Non-Exlusive,复选框不会回到“禁用”状态。
我也试过这个代码:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
这限制了我的复选框,但不响应我的单选按钮。
【问题讨论】:
-
你试过什么?你的具体问题是什么?这不是一个只发布您想要的内容并期望我们为您提供解决方案的网站。
-
请避免在同一个帖子中提出多个问题。而是针对特定问题。
-
@31piy 好吧,所有的问题都合而为一了。
-
您的 jQuery 选择器中的某些类在 html 中不存在。使用您的代码和匹配的 html 创建一个 minimal reproducible example
-
@charlietfl 我将“单个复选框”更改为“复选框”和“复选框”,但它仍然不起作用。我只是想知道是否有一种方法可以将两种解决方案链接到一个完整的代码/字符串中。
标签: javascript html checkbox