我使用以下代码选择页面中的所有复选框:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});在此代码中,选择“所有复选框”。但是,如果我们选择了一些复选框,并给出选择所有它,选择所有。在我们再次取消选中后,选中除上一个复选框之外的所有复选框。
发布于 2017-02-26 08:25:07
attr部分的$('.case').attr('checked', this.checked);不正确:复选框的当前选中状态由checked属性表示。checked属性只是input的 checked state,而不是其当前的选中状态。(就像value属性和value属性之间的区别一样)。
若要设置复选框的当前状态,请使用prop
$(function() {
// add multiple select / deselect functionality
$("#selectall").click(function() {
$('.case').prop('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function() {
$("#selectall").prop("checked", $(".case").length == $(".case:checked").length);
});
});<div><label><input type="checkbox" class="case"> One</label></div>
<div><label><input type="checkbox" class="case"> Two</label></div>
<div><label><input type="checkbox" class="case"> Three</label></div>
<div><label><input type="checkbox" class="case"> Four</label></div>
<div><label><input id="selectall" type="checkbox"> ALL</label></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
https://stackoverflow.com/questions/42466270
复制相似问题