JQuery 复选框全选与反选的例子

发布时间:2020-08-11编辑:脚本学堂
本文介绍了JQuery实现复选框全选与反选的方法,JQuery 复选框checkbox全选与反选的例子,有需要的朋友参考下。

例子,用jquery实现checkbox 复选框的全选、反选(全不选)。
 

复制代码 代码示例:
<!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>
    <title>复选框全选_反选_提交_www.jb200.com</title>
    <style type="text/css">
        #main{width:300px;margin:200px auto;background-color:green;padding:10px;}       
    </style>
    <script src="../js/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            //全选/全不选
            $("#chkAllAndNot").click(function () {
                $(":checkbox[name='love']").attr("checked", $(this).attr("checked"));
            });
            //全选
            $("#btnAll").click(function () {
                $(":checkbox[name='love']").attr("checked", true);
            });
            //全不选
            $("#btnNotAll").click(function () {
                $(":checkbox[name='love']").attr("checked", false);
            });
            //反选
            $("#btnReverse").click(function () {
                var $checks = $(":checkbox[name='love']");
                $checks.each(function (index, item) {
                    item.checked = !item.checked;
                });
            });
            //提交,显示选择的内容
            $("#btnCommit").click(function () {
                var output = "";
                $(":checkbox[name='love']:checked").each(function (index, item) {
                    if (output == "") {
                        output = item.value;
                    }
                    else {
                        output += "," + item.value;
                    }
                });
                alert(output);
            });
        });
    </script>
</head>
<body>
    <div id="main">
        请选择您的爱好:<br />
        <input type="checkbox" id="chkAllAndNot" />全选/全不选<br />
        <input type="checkbox" name="love" value="足球" />足球
        <input type="checkbox" name="love" value="篮球" />篮球
        <input type="checkbox" name="love" value="排球" />排球
        <input type="checkbox" name="love" value="乒乓球" />乒乓球<br />
        <input type="button" value="全选" id="btnAll" />
        <input type="button" value="全不选" id="btnNotAll" />
        <input type="button" value="反选" id="btnReverse" />
        <input type="button" value="提交" id="btnCommit" />
    </div>   
</body>
</html>