layui数据表格checkbox编辑的时候选中

在编辑的时候,比如说一次活动,有很多参与人,编辑这次活动的时候,参与人以弹窗的形式以layui table展示,这需要参与人勾选中,即所谓的数据回显。

以下代码实现了编辑的时候回显,如果是新增的时候,ids为空数组,如果是编辑,则进行初始化,编辑的思路主要是js模拟复选框的click事件,配合layui监听复选框的方法,把需要的数据进行全局缓存存储,实例中主要靠

var ids =new Array();
var names =new Array();
var table_data=new Array();

来维持,代码还实现了分页勾选的记忆功能,layui目前版本还没有实现这一个功能,可以查看我之前发的一篇博客。https://blog.csdn.net/huangbaokang/article/details/80783316

整体代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.jfinal.kit.PropKit" %>
<%
    String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>选择参与人员</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- 引入公共css,js -->
<jsp:include page="/resource/jspf/include_common.jsp"></jsp:include>
<style>
    .search_body{ width:850px; height:600px;}
    .search{width:850px;margin:10px auto;}
</style>
</head>
<body>
<div id="join_in" class="search_body">
    <div class="search">
        <div class="layui-input-inline">
            <input type="text" name="pmName" style="margin-left:15px;" lay-verify="title" autocomplete="off" placeholder="党员姓名"  class="layui-input">
        </div>
        <div class="layui-input-inline">
            <input type="text" name="phone" style="margin-left: 15px;" lay-verify="phone" autocomplete="off" placeholder="手机号"  class="layui-input">
        </div>
        <div class="layui-input-inline">
            <input type="button" style="margin-left:20px;" class="layui-btn layui-btn-danger zh-btn"  btn-search value="查询" />
            <input type="button" class="layui-btn layui-btn-primary zh-btn" btn-renovate value="刷新" />
        </div>
    </div>
    <hr class="layui-bg-gray">
    <button class="layui-btn zh-btn layui-btn-sm layui-btn-danger" btn-confirm style="margin-left:10px;"><i class="layui-icon">&#xe615;</i> 选择党员</button>
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>
<script type="text/html" id="sexTpl">
{{#  if(d.SEX ==0){ }}{{#  } else { }}{{#  } }}
</script>
<script type="text/html" id="imgTpl">
    {{# if(d.HEAD_URL == null){ }}
        <img class="img_ra" src="<%=path%>/resource/images/default.jpg" width="32" height="32"/>
    {{# } else { }}
    <a href='{{d.HEAD_URL}}'  target="_blank"><img  src='{{d.HEAD_URL}}' width="32" height="32"/></a>
    {{# } }}    
</script>
</body>

<script>

var ids =new Array();
var names =new Array();
var table_data=new Array();
var member_ids = '${member_ids}';
var param_names = '${names}';
if(member_ids){
    console.log("编辑过来的");
    // 初始化ids
    ids = member_ids.split(",");
    names = param_names.split(",");
}
    //关闭弹窗
    function Close(windowname){
        var index = parent.layer.getFrameIndex(windowname);
        parent.layer.close(index);
    } 
    layui.use(['form', 'jquery','table'], function(){
        var form = layui.form
                ,layer = layui.layer
                ,$ = layui.jquery
                ,table = layui.table;

      //查询党员
        $('input[btn-search]').on('click',function(){  //全部参与
            var name = $('.search input:eq(0)').val(); //党员name
            var phone = $('.search input:eq(1)').val();//手机号 
            // 发送搜索党员Ajax请求
            tableIns.reload({
                where:{
                    name : name,
                    phone : phone
                }
             });
        });
        //刷新
        $('input[btn-renovate]').on('click',function(){  //部分参与
            $('.search input:eq(0)').val('');
            $('.search input:eq(1)').val('');
            tableIns.reload({
                where:{
                    name : "",
                    phone : ""
                }
             });
        });
        //确定选择的党员
        $('button[btn-confirm]').on('click',function(){ 
            var str=""; //参与人姓名拼串
            var member_ids="";
            if(ids.length==0){
                layer.alert("请选择参与人");
                return;
            }
            console.log("组织生活参与人一共选择了"+ids.length+" 个");
            console.log(names);
            for(var i=0;i<ids.length;i++){
                if(i<ids.length-1){
                    str += names[i]+",";
                    member_ids += ids[i]+",";
                }else{
                    str += names[i];
                    member_ids += ids[i];
                }
            }
            parent.document.getElementById("joinpm").value=str;  //将参与人员传到父级输入框
            parent.document.getElementById("join_member_ids").value = member_ids;
            Close(window.name);//关闭弹窗

        });





        var tableIns = table.render({
            elem: '#test'
                ,url:'<%=path%>/partyMember/getPartyMembersByOrgCode' 
                , width: '100%'
                , height: 480
                ,id:'PM_CODE'
            ,cols: [[ //标题栏
                {checkbox: true, LAY_CHECKED: false, filter:'test'}
                , {field: 'PM_CODE', title: 'PM_CODE', width: 180, align: 'center'} 
                , {field: 'HEAD_URL', title: '头像', width: 100, align: 'center',templet:'#imgTpl'}
                , {field: 'NAME', title: '党员姓名', width: 180, align: 'center'}
                , {field: 'ORG_NAME', title: '组织机构', width: 180, align: 'center'}
                , {field: 'MOBILE_NO', title: '手机号', width: 120, align: 'center'}
                , {field: 'SEX', title: '性别', width: 80, align: 'center',templet:'#sexTpl'}
            ]]
            , page: true //是否显示分页
            ,limits : [ 10, 20,50, 100 ],
            limit : 10
            ,done:function(res,curr,count){
                $('table tr').on('click',function(){
                     $('table tr').css('background','');
                     $(this).css('background','<%=PropKit.use("config.properties").get("table_color")%>');
                 });
                // 隐藏列
                $(".layui-table-box").find("[data-field='PM_CODE']").css("display","none");
                 table_data=res.data;
                 var stat = true;

                //在缓存中找到PM_CODE ,然后设置data表格中的选中状态
                //循环所有数据,找出对应关系,设置checkbox选中状态
                for(var i=0;i<res.data.length;i++){
                    for(var j=0;j<ids.length;j++){
                        if(res.data[i].PM_CODE==ids[j]){
                            //这里才是真正的有效勾选
                            //res.data[i]["LAY_CHECKED"]=true;
                            //找到对应数据改变勾选样式,呈现出选中效果
                            var index= res.data[i]['LAY_TABLE_INDEX'];
                            $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                            $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                        }
                    }
                }
                //设置全选checkbox的选中状态,只有改变LAY_CHECKED的值, table.checkStatus才能抓取到选中的状态
                var checkStatus = table.checkStatus('test');
                if(checkStatus.isAll){
                    $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                    $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                }


                 /* for(var j=0; j < ids.length; j++){
                     for (var i=0;i< res.data.length;i++) {

                         //数据id和要勾选的id相同时checkbox选中
                         if(ids[j] == res.data[i].PM_CODE){
                             $('.layui-table-body tbody tr').each(function(index,elem){
                                if($(elem).children('td[data-field="PM_CODE"]').children('div').html() == ids[j]){
                                     $(elem).children('td[data-field="0"]').children('div').children('div').click();
                                     stat = false;
                                     return false;
                                 }
                             });
                         }

                     }
                     if(!stat){
                         continue;
                     }
                 } */

            }
          });

        //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组 
        table.on('checkbox(test)', function (obj) {
           if(obj.checked==true){
               if(obj.type=='one'){
                   if($.inArray(obj.data.PM_CODE,ids) == -1){
                       ids.push(obj.data.PM_CODE);
                       names.push(obj.data.NAME);
                   }

               }else{
                   for(var i=0;i<table_data.length;i++){

                       if($.inArray(table_data[i].PM_CODE,ids) == -1){
                           ids.push(table_data[i].PM_CODE);
                           names.push(table_data[i].NAME);
                       }

                   }
               }

           }else{
               if(obj.type=='one'){
                   for(var i=0;i<ids.length;i++){
                      if(ids[i]==obj.data.PM_CODE){
                           ids.splice(i,1);
                           names.splice(i,1);
                       }
                  }
               }else{
                   for(var i=0;i<ids.length;i++){
                       for(var j=0;j<table_data.length;j++){
                           if(ids[i]==table_data[j].PM_CODE){
                               ids.splice(i,1);
                               names.splice(i,1);
                          }
                       }
                   }
               }

           }

        });

    });



</script>
</html>

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/81983930