繁体   English   中英

使用jquery选中并取消选中所有复选框

[英]Check and uncheck all checkboxes with jquery

我正在使用此脚本来检查并取消选中所有复选框:

$('#checkall').click(function () {
    var checked = $(this).data('checked');
    $('.chkall').find(':checkbox').attr('checked', !checked);
    $(this).data('checked', !checked);
});

它工作得很好,但是一旦我在“全部检查”之后取消选中几个选中的复选框,然后再次点击“取消全部检查”和“全部检查”,则不再检查那些以前未选中的复选框。 帮助会很棒! 非常感谢你!

这可能是正确的方法..

使用prop而不是attr并将div中的复选框列表分组,仅用于组织目的。 也可以使用原样checked ,不要否定它。

 $(document).ready(function() { $('#checkall').click(function() { var checked = $(this).prop('checked'); $('#checkboxes').find('input:checkbox').prop('checked', checked); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="checkall" /> <label for="checkall">check / uncheck all</label> <br/> <br/> <div id="checkboxes"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> 

 $('#checkall').click(function(){ var d = $(this).data(); // access the data object of the button $(':checkbox').prop('checked', !d.checked); // set all checkboxes 'checked' property using '.prop()' d.checked = !d.checked; // set the new 'checked' opposite value to the button's data object }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='checkall' data-checked='false'>check/uncheck all</button> <input type=checkbox> <input type=checkbox> <input type=checkbox> <input type=checkbox> <input type=checkbox> 


我根据触发按钮猜测了你的HTML是什么样的,但我不知道你最初是如何在其上设置data 希望这是你编码的方式。 如果没有,请告诉我。

您只需要获取所有复选框并检查它们。

 $('#checkall').click(function() { var _this = this; $('#checkboxes').find('input[name="checkAll"]').each(function() { if ($(_this).is(':checked')) { $(this).prop('checked', true); } else { $(this).prop('checked', false); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="checkall" /> <label for="checkall">check / uncheck all</label> <br/> <br/> <div id="checkboxes" class=".chkall"> <input type="checkbox" name="checkAll"/> <input type="checkbox" name="checkAll"/> <input type="checkbox" name="checkAll" /> <input type="checkbox" name="checkAll" /> <input type="checkbox" name="checkAll" /> <input type="checkbox" name="checkAll" /> <input type="checkbox" name="checkAll" /> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM