【发布时间】:2013-06-24 14:34:50
【问题描述】:
所以,我有六个复选框,其中一个被默认选中。用户一次只能检查两个复选框,这很好用。但是,如果选中了默认复选框,则不应选中其他复选框。这就是给我带来问题的原因。我找到了this post 并尝试从那里开始工作。
所以,我有 5 个类别为 other 的复选框和一个 id 为 default 的复选框。我的问题是,当其他人都没有被检查时,我无法检查default。
这是带有代码的JSFiddle——你们能把我推向正确的方向吗?
这是我的代码:
HTML:
<input type="checkbox" group="checkboxes" name="other" class="other" id="one">
<label for="one">One</label><br />
<input type="checkbox" group="checkboxes" name="other" class="other" id="two">
<label for="two">Two</label><br />
<input type="checkbox" group="checkboxes" name="other" class="other" id="three">
<label for="three">Three</label><br />
<input type="checkbox" group="checkboxes" name="other" class="other" id="four">
<label for="four">Four</label><br />
<input type="checkbox" group="checkboxes" name="other" class="other" id="five">
<label for="five">Five</label><br />
<input group="checkboxes" type="checkbox" checked="checked" name="other" id="default">
<label for="default">Default</label>
jQuery:
$('.other').change(function(){
var c = this.checked ? false : true;
$('#default').attr('checked', c);
});
$(document).ready(function(){
var maxaids = "2";
$(document).on('click', "input[type=checkbox]", function(){
var bol = $("input:checked").length >= maxaids;
$("input[type=checkbox]").not(":checked").attr("disabled",bol);
});
});
【问题讨论】:
-
+1 以获得清晰的描述和一个有趣的问题
-
this.checked ? false : true;有点过分了。此外,除非您使用的是旧版本的 jQuery;使用prop()而不是attr() -
只是好奇如果取消选中“默认”会发生什么?
-
其实默认是一个隐藏的复选框,只是不想把事情复杂化:)所以不能取消勾选。