jQuery对复选框(checkbox)的全选,全不选,反选等的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery.v2.2.2.min.js"></script>
</head>
<body>
<script>
    $(function() {

        //全选/全不选
        $("#all").click(function() {
            $("[name=items]:checkbox").attr("checked", this.checked);
        });
        $("[name=items]:checkbox").click(function() {
            var flag = true;
            $("[name=items]:checkbox").each(function() {
                if(!this.checked) {
                    flag = false;
                }
            });
            $("#all").attr("checked", flag);
        })
        //全选
        $("#selectAll").click(function() {
            $("[name=items]:checkbox").each(function() {
                $(this).attr("checked", true);
            });
        });
        //全不选
        $("#unSelect").click(function() {
            $("[name=items]:checkbox").each(function() {
                $(this).attr("checked", false);
            });
        });
        //反选
        $("#reverse").click(function() {
            $("[name=items]:checkbox").each(function() { //遍历每一个复选框
                //$(this).attr("checked",!$(this).attr("checked")); //jQuery方法取复选框的反向值
                this.checked = !this.checked; //js方法
            });
        });
        //输出选中的值
        $("#btn").click(function() {
            var str = "你选中的是:\r\n";
            $("[name=items]:checkbox:checked").each(function() {
                str += $(this).val() + "\r\n";
            });
            alert(str);
        });
    })
</script>
<ul id="list">
    <li><label><input type="checkbox" name="items" value="1"> 1.时间都去哪儿了</label></li>
    <li><label><input type="checkbox" name="items" value="2"> 2.海阔天空</label></li>
    <li><label><input type="checkbox" name="items" value="3"> 3.真的爱你</label></li>
    <li><label><input type="checkbox" name="items" value="4"> 4.不再犹豫</label></li>
    <li><label><input type="checkbox" name="items" value="5"> 5.光辉岁月</label></li>
    <li><label><input type="checkbox" name="items" value="6"> 6.喜欢妳</label></li>
</ul>
<input type="checkbox" id="all"> 全选/全不选</br>
<input type="button" value="全选" class="btn" id="selectAll">
<input type="button" value="全不选" class="btn" id="unSelect">
<input type="button" value="反选" class="btn" id="reverse">
<input type="button" value="获得选中的所有值" id="btn" id="getValue">
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值