layui使用tableSelect插件实现下拉框表格,并多选或单选数据
HTML代码:
<!-- 部分代码 -->
<tr>
<td><label class="layui-form-label required">巡防点</label></td>
<td>
<input type="text" name="point" class="layui-input" lay-verify="required" lay-reqtext="请选择巡防点" autocomplete="off" value="{$row.point|default=''}" id="point" ts-selected="{$row.point_id|default=''}">
<input type="hidden" name="point_id" value="{$row.point_id|default=''}">
</td>
<td><label class="layui-form-label required">巡防人员</label></td>
<td>
<input type="text" name="patrol" class="layui-input" lay-verify="required" lay-reqtext="请选择巡防人员" autocomplete="off" value="{$row.patrol|default=''}" id="patrol" ts-selected="{$row.patrol_id|default=''}">
<input type="hidden" name="patrol_id" value="{$row.patrol_id|default=''}">
</td>
</tr>
JS代码部分:
<script src="__STATIC__/jquery.min.js?v={$version}" charset="utf-8"></script>
<script>
layui.config({
base: '/static/plugs/layui-v2.5.6/ext/',// 第三方模块所在目录
version: '' // 插件版本号
}).extend({
tableSelect:'tableSelect', // 插件
});
// 使用插件
layui.use(['form','table','laypage','layer','tableSelect'], function() {
point();
patrol();
//巡防点
function point() {
var tableSelect = layui.tableSelect;
tableSelect.render({
elem: '#point',
size: 'sm',//定义输入框input对象 必填
checkedKey: 'id', //表格的唯一建值,非常重要,影响到选中状态 必填
searchKey: 'keyword', //搜索输入框的name值 默认keyword
searchPlaceholder: '关键词搜索', //搜索输入框的提示文字 默认关键词搜索
page:false,
table: { //定义表格参数,与LAYUI的TABLE模块一致,只是无需再定义表格elem
page:false,
url:'/admin/yuanqu.patrolPoint/getPoint?sjkey=0',
cols: [[
{type: 'checkbox' },
{field:'id',title:'编号',width:60,sortable:true},
{field:'point',title:'巡防点名称',minWidth:150,sortable:true},
{field:'adress',title:'巡防点地址',minWidth:150,sortable:true},
]],
done: function (res, curr, count) {
}
},
done: function (elem, data) {
var NEWJSON = []; // 下拉框的输入的值
var idjson=[];
layui.each(data.data, function (index, item) {
NEWJSON.push(item.point);
idjson.push(item.id);
})
elem.val(NEWJSON.join(",")); // 下拉框里面显示选中的值
$('input[name="point_id"]').val(idjson.join(","));
}
})
}
//巡防人员
function patrol() {
var tableSelect = layui.tableSelect;
tableSelect.render({
elem: '#patrol',
size: 'sm',//定义输入框input对象 必填
checkedKey: 'id', //表格的唯一建值,非常重要,影响到选中状态 必填
searchKey: 'keyword', //搜索输入框的name值 默认keyword
searchPlaceholder: '关键词搜索', //搜索输入框的提示文字 默认关键词搜索
page:false,
table: { //定义表格参数,与LAYUI的TABLE模块一致,只是无需再定义表格elem
page:false,
url:'/admin/yuanqu.patrol/getPatrol?sjkey=0',
cols: [[
{type: 'radio' },
{field:'id',title:'编号',width:60,sortable:true},
{field:'realname',title:'名称',minWidth:100,sortable:true},
{field:'gender',title:'性别',minWidth:80, sortable:true},
{field:'phone',title:'手机号',minWidth:120, sortable:true},
]]
},
done: function (elem, data) {
var NEWJSON = [];
var idjson=[]
layui.each(data.data, function (index, item) {
NEWJSON.push(item.realname);
idjson.push(item.id);
})
elem.val(NEWJSON.join(",")); // 下拉框里面显示选中的值
$('input[name="patrol_id"]').val(idjson.join(","));
}
})
}
})
</script>
tableSelect.js插件
layui.define(['table', 'jquery', 'form'], function (exports) {
// "use strict";
var MOD_NAME = 'tableSelect',
$ = layui.jquery,
table = layui.table,
form = layui.form;
var tableSelect = function () {
this.v = '1.1.0';
this.cacheObj ={};
};
/**
* 初始化表格选择器
*/
tableSelect.prototype.render = function (opt) {
var elem = $(opt.elem);
var tableDone = opt.table.done || function(){};
//默认设置
opt.searchKey = opt.searchKey || 'keyword';
opt.searchPlaceholder = opt.searchPlaceholder || '关键词搜索';
opt.checkedKey = opt.checkedKey;
opt.table.page = opt.table.page==undefined?true:opt.table.page;
opt.table.size = "sm";
opt.table.height = opt.table.height || 315;
var functionVar=function(e) {
e.stopPropagation();
if(document.getElementById("tableSelectSearchInput")){
$("#tableSelectSearchInput").val(elem.val())
var e = document.createEvent("Event");
e.initEvent("oninput", true, true);
document.getElementById("tableSelectSearchInput").dispatchEvent(e);
$("#tableSelectSearchInput").trigger("oninput");
}
if($('div.tableSelect').length >= 1){
return false;
}
var t = elem.offset().top + elem.outerHeight()+"px";
var l = elem.offset().left +"px";
var tableName = "tableSelect_table_" + new Date().getTime();
var tableBox = '<div class="tableSelect layui-anim layui-anim-upbit" style="left:'+l+';top:'+t+';border: 1px solid #d2d2d2;background-color: #fff;box-shadow: 0 2px 4px rgba(0,0,0,.12);padding:10px 10px 0 10px;position: absolute;z-index:66666666;margin: 5px 0;border-radius: 2px;min-width:530px;">';
tableBox += '<div class="tableSelectBar">';
tableBox += '<form lay-filter="tableSelectForm" id="tableSelectForm" class="layui-form" action="" style="display:inline-block;">';
tableBox += '<input id="tableSelectSearchInput" οninput="layui.tableSelect.searchInput(\''+tableName+'\');" style="display:inline-block;width:190px;height:26px;vertical-align:middle;margin-right:-1px;border: 1px solid #C9C9C9;" type="text" name="'+opt.searchKey+'" placeholder="'+opt.searchPlaceholder+'" autocomplete="off" class="layui-input"><button class="layui-btn layui-btn-sm layui-btn-primary tableSelect_btn_search" lay-submit lay-filter="tableSelect_btn_search"><i class="layui-icon layui-icon-search"></i></button>';
tableBox += '</form>';
tableBox += '<button style="float:right;" class="layui-btn layui-btn-sm tableSelect_btn_select">选择<span></span></button>';
tableBox += '</div>';
tableBox += '<table id="'+tableName+'" lay-filter="'+tableName+'"></table>';
tableBox += '</div>';
tableBox = $(tableBox);
$('body').append(tableBox);
//数据缓存
var checkedData = [];
//渲染TABLE
opt.table.elem = "#"+tableName;
opt.table.id = tableName;
opt.table.done = function(res, curr, count){
defaultChecked(res, curr, count);
setChecked(res, curr, count);
tableDone(res, curr, count);
};
var tableSelect_table = table.render(opt.table);
tableSelect.cacheObj[tableName]=tableSelect_table;
//分页选中保存数组
table.on('radio('+tableName+')', function(obj){
if(opt.checkedKey){
checkedData = table.checkStatus(tableName).data
}
updataButton(table.checkStatus(tableName).data.length)
})
table.on('checkbox('+tableName+')', function(obj){
if(opt.checkedKey){
if(obj.checked){
for (var i=0;i<table.checkStatus(tableName).data.length;i++){
checkedData.push(table.checkStatus(tableName).data[i])
}
}else{
if(obj.type=='all'){
for (var j=0;j<table.cache[tableName].length;j++) {
for (var i=0;i<checkedData.length;i++){
if(checkedData[i][opt.checkedKey] == table.cache[tableName][j][opt.checkedKey]){
checkedData.splice(i,1)
}
}
}
}else{
//因为LAYUI问题,操作到变化全选状态时获取到的obj为空,这里用函数获取未选中的项。
function nu (){
var noCheckedKey = '';
for (var i=0;i<table.cache[tableName].length;i++){
if(!table.cache[tableName][i].LAY_CHECKED){
noCheckedKey = table.cache[tableName][i][opt.checkedKey];
}
}
return noCheckedKey
}
var noCheckedKey = obj.data[opt.checkedKey] || nu();
for (var i=0;i<checkedData.length;i++){
if(checkedData[i][opt.checkedKey] == noCheckedKey){
checkedData.splice(i,1);
}
}
}
}
checkedData = uniqueObjArray(checkedData, opt.checkedKey);
updataButton(checkedData.length)
}else{
updataButton(table.checkStatus(tableName).data.length)
}
});
//渲染表格后选中
function setChecked (res, curr, count) {
for(var i=0;i<res.data.length;i++){
for (var j=0;j<checkedData.length;j++) {
if(res.data[i][opt.checkedKey] == checkedData[j][opt.checkedKey]){
res.data[i].LAY_CHECKED = true;
var index= res.data[i]['LAY_TABLE_INDEX'];
var checkbox = $('#'+tableName+'').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
checkbox.prop('checked', true).next().addClass('layui-form-checked');
var radio = $('#'+tableName+'').next().find('tr[data-index=' + index + '] input[type="radio"]');
radio.prop('checked', true).next().addClass('layui-form-radioed').find("i").html('');
}
}
}
var checkStatus = table.checkStatus(tableName);
if(checkStatus.isAll){
$('#'+tableName+'').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
$('#'+tableName+'').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
}
updataButton(checkedData.length)
}
//写入默认选中值(puash checkedData)
function defaultChecked (res, curr, count){
if(opt.checkedKey && elem.attr('ts-selected')){
var selected = elem.attr('ts-selected').split(",");
for(var i=0;i<res.data.length;i++){
for(var j=0;j<selected.length;j++){
if(res.data[i][opt.checkedKey] == selected[j]){
checkedData.push(res.data[i])
}
}
}
checkedData = uniqueObjArray(checkedData, opt.checkedKey);
}
}
//更新选中数量
function updataButton (n) {
tableBox.find('.tableSelect_btn_select span').html(n==0?'':'('+n+')')
}
//数组去重
function uniqueObjArray(arr, type){
var newArr = [];
var tArr = [];
if(arr.length == 0){
return arr;
}else{
if(type){
for(var i=0;i<arr.length;i++){
if(!tArr[arr[i][type]]){
newArr.push(arr[i]);
tArr[arr[i][type]] = true;
}
}
return newArr;
}else{
for(var i=0;i<arr.length;i++){
if(!tArr[arr[i]]){
newArr.push(arr[i]);
tArr[arr[i]] = true;
}
}
return newArr;
}
}
}
//FIX位置
var overHeight = (elem.offset().top + elem.outerHeight() + tableBox.outerHeight() - $(window).scrollTop()) > $(window).height();
var overWidth = (elem.offset().left + tableBox.outerWidth()) > $(window).width();
overHeight && tableBox.css({'top':'auto','bottom':'0px'});
overWidth && tableBox.css({'left':'auto','right':'5px'})
//关键词搜索
form.on('submit(tableSelect_btn_search)', function(data){
tableSelect_table.reload({
where: data.field
// page: {
// curr: 1
// }
});
return false;
});
//双击行选中
table.on('rowDouble('+tableName+')', function(obj){
var checkStatus = {data:[obj.data]};
selectDone(checkStatus);
})
//按钮选中
tableBox.find('.tableSelect_btn_select').on('click', function() {
var checkStatus = table.checkStatus(tableName);
if(checkedData.length > 1){
checkStatus.data = checkedData;
}
selectDone(checkStatus);
})
//写值回调和关闭
function selectDone (checkStatus){
if(opt.checkedKey){
var selected = [];
for(var i=0;i<checkStatus.data.length;i++){
selected.push(checkStatus.data[i][opt.checkedKey])
}
elem.attr("ts-selected",selected.join(","));
}
opt.done(elem, checkStatus);
tableBox.remove();
delete table.cache[tableName];
checkedData = [];
}
//点击其他区域关闭
$(document).mouseup(function(e){
var userSet_con = $(''+opt.elem+',.tableSelect');
if(!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0){
tableBox.remove();
delete table.cache[tableName];
delete tableSelect.cacheObj[tableName];
checkedData = [];
}
});
}
elem.off('click').on('click',functionVar);
elem.off('input').on('input',functionVar);
}
/**
* 隐藏选择器
*/
tableSelect.prototype.hide = function (opt) {
$('.tableSelect').remove();
}
tableSelect.prototype.searchInput = debounce(function (seltablename) {
tableSelect.cacheObj[seltablename].reload({
where: form.val("tableSelectForm")
// page: {
// curr: 1
// }
});
},100)
// 第四版(立即执行,停止触发 n 秒后,才可以重新触发执行。反过来)
function debounce(func, wait, immediate) {
// immediate默认为false
var timeout, args, context, timestamp, result;
var later = function() {
// 当wait指定的时间间隔期间多次调用_.debounce返回的函数,则会不断更新timestamp的值,导致last < wait && last >= 0一直为true,从而不断启动新的计时器延时执行func
var last = Date.now() - timestamp;
if(last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if(!immediate) {
result = func.apply(context, args);
if(!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = Date.now();
// 第一次调用该方法时,且immediate为true,则调用func函数
var callNow = immediate && !timeout;
// 在wait指定的时间间隔内首次调用该方法,则启动计时器定时调用func函数
if(!timeout) timeout = setTimeout(later, wait);
if(callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
//自动完成渲染
var tableSelect = new tableSelect();
//FIX 滚动时错位
if(window.top == window.self){
$(window).scroll(function () {
tableSelect.hide();
});
}
exports(MOD_NAME, tableSelect);
})
效果图示: