如何用jQuery实现checkbox全选

有2个button,
第一个,点击一次实现页面中checkbox全选,再点击一次全部取消。
第二个,点击一次实现页面中checkbox反选。
用jquery如何实现?求助大神们

全选:

$(":checkbox").attr("checked","checked");

全不选:

$(":checkbox").removeAttr("checked");

 

反选:

$(":checkbox:checked").removeAttr("checked");

$(":checkbox:not(:checked)").attr("checked","checked");

 

全手写,没有经过测试。

 

完整代码如下,测试通过:

<html>
<head>
    <title>如何用jQuery实现checkbox全选</title>
    <script src="jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        //全选,全不选
        function allSelect() {
            if ($(":checkbox").attr("checked") != "checked") {
                $(":checkbox").attr("checked", "checked");
            }
            else {
                $(":checkbox").removeAttr("checked");
            }
        }
        //反选
        function otherSelect() {
            $(":checkbox").each(function () {
                if ($(this).attr("checked") == "checked") {
                    $(this).removeAttr("checked");
                }
                else {
                    $(this).attr("checked", "checked");
                }
            });
        }
    </script>
</head>
<body>
    <input id="Checkbox1" type="checkbox" />
    <input id="Checkbox2" type="checkbox" />
    <input id="Checkbox3" type="checkbox" />
    <input id="Checkbox4" type="checkbox" />
    <input id="Checkbox5" type="checkbox" />
    <input id="Button1" type="button" value="全选" onclick="allSelect();" />
    <input id="Button3" type="button" value="反选" onclick="otherSelect();" />
</body>
</html>

追问

$('#select_all').click(function () {//全选
$(":checkbox").attr("checked","checked");
});
select all
这样写,无法实现哪里有问题呢?

追答

没有问题,可以全选,加载时注册:
//加载时注册事件
$(function()
{
$('#select_all').click(function () {//全选
$(":checkbox").attr("checked", "checked");
});
});

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-03-31

全选:

&#36;(":checkbox").attr("checked","checked");

$("#selectAll").click(function(){

if($(this).attr("checked")){

$("input:checkbox").attr("checked","checked");

}else{

$("input:checkbox").removeAttr("checked");

}

});

本回答被网友采纳
第2个回答  2013-10-08
<script src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
    $(':button').toggle(function(){
        $(':checkbox').attr('checked',"checked");
    },function(){
        $(':checkbox').removeAttr('checked');
    })

})
</script>

就用这个就可以了

相似回答