layui.use('table', function () {
let table = layui.table
, form = layui.form
, $ = layui.$;
// Set a global variable to hold the selected line information
let ids = new Array();
// Save all the data ids of the current page, used when clicking select all
let tableIds = new Array();
table.render({
elem: '#test'
, url: '/demo/girl/list/'
, cols: [[
{type: 'checkbox', width: 70}
, {field: 'id', title: 'ID'}
, {field: 'age', title: 'Age'}
, {field: 'city', title: 'The City'}
]]
, request: {
pageName: 'current' //Parameter name for page number, default: page
, limitName: 'size' // parameter name of the amount of data per page, default: limit
}
, page: true
, done: function (res) {
// Set all the data ids of the current page to a global variable.
tableIds = res.data.map(function (value) {
return value.id;
});
// Set the current page selection
$.each(res.data, function (idx, val) {
if (ids.indexOf(val.id) > -1) {
val["LAY_CHECKED"] = 'true';
//Find the corresponding data to change the check style to show the selected effect.
let index = val['LAY_TABLE_INDEX'];
$('tr[data-index=' + index + '] input[type="checkbox"]').click();
form.render('checkbox'); // Refresh checkbox selector box rendering
}
});
// Get the checkbox status of the form, and set the checkbox to be checked when all are checked.
let checkStatus = table.checkStatus('test');
if (checkStatus.isAll) {
$('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
form.render('checkbox'); // Refresh checkbox selector box rendering
}
}
});
// Listen for tick events
table.on('checkbox(test)', function (obj) {
if (obj.checked == true) {
if (obj.type == 'one') {
ids.push(obj.data.id);
} else {
for (let i = 0; i < tableIds.length; i++) {
//When the full selection before the selected part of the line to determine, to avoid repetition
if (ids.indexOf(tableIds[i]) == -1) {
ids.push(tableIds[i]);
}
}
}
} else {
if (obj.type == 'one') {
let i = ids.length;
while (i--) {
if (ids[i] == obj.data.id) {
ids.splice(i, 1);
}
}
} else {
let i = ids.length;
while (i--) {
if (tableIds.indexOf(ids[i]) != -1) {
ids.splice(i, 1);
}
}
}
}
});
})