JQuery实现CheckBox全选全不选

时间:2022-01-04 09:32:35

做项目时需要实现CheckBox的全选,我想用JQuery实现,从网上找了找,网上的确有很多例子,但都不能实现我想要的全部效果,所以我就参照网上的例子试着自己写了一个,达到了自己想要的效果,其实这也是一个很简单的例子,其中有不足的地方还望大家能够给予指出。下面把代码贴出来给大家看看

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="checkAll.aspx.cs" Inherits="checkAll" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Js/jquery-1.5.2.js" type="text/javascript"></script>
    <script src="Js/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            //全选或全不选
            $("#chkAll").click(function () {//当点击全选框时
                var flag = $("#chkAll").attr("checked");//判断全选按钮的状态
                $("[id$='Item']").each(function () {//查找每一个Id以Item结尾的checkbox
                    $(this).attr("checked", flag);//选中或者取消选中
                });
            });
            //如果全部选中勾上全选框,全部选中状态时取消了其中一个则取消全选框的选中状态
            $("[id$='Item']").each(function () {
                $(this).click(function () {
                    if ($("[id$='Item']:checked").length == $("[id$='Item']").length) {
                        $("#chkAll").attr("checked", "checked");
                    }
                    else $("#chkAll").removeAttr("checked");
                });

            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td width="100px">
                <asp:CheckBox ID="chkAll" runat="server" Text="全选"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk1_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk2_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk3_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk4_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk5_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk6_Item" runat="server"/>
            </td>
        </tr>
         <tr>
            <td width="100px">
                <asp:CheckBox ID="chk7_Item" runat="server"/>
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>