Layui Bulk Delete: How to Remove Table Data
To achieve batch deletion of table data in layui, you can follow these steps:
- Add a checkbox column to the table for selecting multiple data entries.
- Add an event listener to each checkbox in the checkbox list, so that when a checkbox is checked, the ID of the data is stored in an array.
- Create a delete button that, when clicked, will retrieve the array of selected data IDs and send a request to the backend for bulk deletion.
Here is a simple example code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>批量删除表格数据</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.css">
</head>
<body>
<div class="layui-container">
<button class="layui-btn layui-btn-danger" id="deleteBtn">批量删除</button>
<table id="dataTable" lay-filter="dataTable"></table>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.js"></script>
<script>
layui.use(['table', 'layer'], function() {
var table = layui.table;
var layer = layui.layer;
// 模拟表格数据
var data = [
{id: 1, name: '张三'},
{id: 2, name: '李四'},
{id: 3, name: '王五'}
];
// 渲染表格
table.render({
elem: '#dataTable',
cols: [[
{type: 'checkbox'},
{field: 'id', title: 'ID'},
{field: 'name', title: '姓名'}
]],
data: data
});
// 监听复选框选中事件
table.on('checkbox(dataTable)', function(obj) {
var checkStatus = table.checkStatus('dataTable');
var ids = checkStatus.data.map(function(item) {
return item.id;
});
console.log(ids);
});
// 监听删除按钮点击事件
document.getElementById('deleteBtn').addEventListener('click', function() {
var checkStatus = table.checkStatus('dataTable');
var ids = checkStatus.data.map(function(item) {
return item.id;
});
console.log('要删除的id数组:', ids);
// 发送请求给后端进行批量删除操作
});
});
</script>
</body>
</html>
In the example code above, we capture the selected data ID array by monitoring the selection event of the checkbox, and then perform corresponding operations using this array when the delete button is clicked. Feel free to modify and extend the code according to your needs.