• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

jquery实现checkbox的单选和全选

武飞扬头像
胡胡胡胡虎
帮助1

一、思路

全选:判断“全选”checkbox的状态,如果选中则把tbody下所有的checkbox选中,反之

单选:主要是判断有没有全选,如果不是选中状态就把全选的checkbox状态设置为false,如果是选中就拿所有选中状态下“name=id”的chekbox和所有‘’name=id"的数量去比较,如果一样表示全选了,设置全选的chekbox为选中状态,反之。

二、代码

1.css部分,直接搬运的django项目里面的。

<table border="2" style="margin: 0 auto;text-align: left;width: 800px">
        <thead>
        <tr>
            <th><input type="checkbox" name="all">全选</th>
            <th>id</th>
            <th>用户名</th>
            <th>昵称</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="tb">
        {% for user in userlist %}
            <tr>
                <td><input type="checkbox" name="id" value="{{ user.UserID }}" οnclick="userCheck(this)"></td>
                <td>{{ user.UserID }}</td>
                <td>{{ user.Username }}</td>
                <td>{{ user.NickName }}</td>
                <td>{{ user.Email }}</td>
                <td>{{ user.Role.RoleName }}</td>
                <td>
                    <img id="update" src="https://blog.csdn.net/static/img/edit-new.png" οnclick="getUser({{ user.UserID }})">
                    <img id="delete" src="https://blog.csdn.net/static/img/edit_remove.png" οnclick="userdelete({{ user.UserID }})">
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
学新通

2.js部分,name和id都可以根据实际修改

$(function () {
    //全选,设置chheckbox name='all' tbody id=tb
    $("input[name=all]").click(function () {
        if (this.checked) {
            $("#tb :checkbox").prop("checked", true);
        } else {
            $("#tb :checkbox").prop("checked", false);
        }
    });
});
//单选 设置name=id
function userCheck(ths) {
    if (ths.checked == false) {
        $("input[name=all]:checkbox").prop('checked', false);
    }
    else {
        var count = $("input[name='id']:checkbox:checked").length;
        if (count == $("input[name='id']:checkbox").length) {
            $("input[name=all]:checkbox").prop("checked", true);
        }
    }
}
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhifbcia
系列文章
更多 icon
同类精品
更多 icon
继续加载