快捷搜索:   nginx

jquery实现多选框 全选 取消全选 自动勾选 自动去除勾选状态

主要实现以下功能

    【全选/取消】点击全选框后,下面的子复选框全部选中。取消全选框勾选后,下面的子复选框全部取消选中。
     当所有子复选框均被选中后,全选框自动勾选为选中状态。当某个子复选框被取消选中后,全选框自动取消勾选状态。

如下图:

1.gif
代码如下:
html 代码

<table>
 <thead>
     <tr>
        <th>序号<input type="checkbox" class="loginName" id="all"></th>
        <th>员工号</th>
        <th>用户名称</th>
    </tr>
</thead>
<tbody id="checklist">
   <g:each in="${users}" var="user" status="index">
          <tr class='table-c' userId="${user.id}" userName="${user.name}">
                <td>${index + 1}
                     <input type="checkbox" name="loginName" class="loginName"  value="${user.id}" >
                </td>
                <td>${user.loginName}</td>
                <td>${user.name}</td>
          </tr>
   </g:each>
</tbody>
</table>


    注意:全选框ID:all ; 子复选框最外层的ID 为:chekclist

JS代码

注意:Jquery.js记得引入,这里没写,放到页面底部

<script>
$(function(){
          /*全选按钮状态显示判断*/
      $("#checklist").find("input[type='checkbox']").click(function(){
           /*初始化选择为TURE*/
           $("#all")[0].checked = true;
           /*获取未选中的*/
           var nocheckedList = new Array();
           $("#checklist").find('input:not(:checked)').each(function() {
               nocheckedList.push($(this).val());
           });
           /*状态显示*/
           if (nocheckedList.length == $("#checklist").find('input').length) {
               $("#all")[0].checked = false;
           }else if(nocheckedList.length ==0){
               $("#all")[0].checked = true;
           }else if(nocheckedList.length){
               $("#all")[0].checked = false;
           }
     });
     // 全选/取消
    $("#all").click(function(){
       // alert(this.checked);
        if ($(this).is(':checked')) {
               $("#checklist").find('input').each(function(){
                    $(this).prop("checked",true);
               });
         } else {
              $("#checklist").find('input').each(function(){
                    $(this).removeAttr("checked",false);
                    // 根据官方的建议:具有 true 和 false 两个属性的属性,
                    // 如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()
                    $(this).prop("checked",false);
              });
         }
   });
});
</script>


顶(0)
踩(1)

您可能还会对下面的文章感兴趣:

最新评论