How to implement the editing feature in the layui data table?

To enable editing functionality for the Layui data table, you need to follow these steps:

  1. Include the necessary resources for Layui in an HTML page, such as the CSS and JS files for Layui.
  2. HTML table
  3. display the table
  4. When the table is edited, perform the following action.
  5. In the event callback function, you can use AJAX requests to submit the edited data to the backend for saving.
  6. revise
  7. What you need to type in.
  8. modify the table
  9. alter the table

The sample code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css" />
  <script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
  <title>Layui数据表格编辑功能示例</title>
</head>
<body>
  
  <table id="demo" lay-filter="test"></table>

  <script>
    layui.use(['table', 'form'], function(){
      var table = layui.table;

      // 渲染数据表格
      table.render({
        elem: '#demo',
        url: '/api/data',
        cols: [[
          {field: 'id', title: 'ID', edit: 'text'},
          {field: 'name', title: '姓名', edit: 'text'},
          {field: 'age', title: '年龄', edit: 'text'},
          {field: 'email', title: '邮箱', edit: 'text'},
          {fixed: 'right', title:'操作', toolbar: '#barDemo'}
        ]],
        page: true
      });

      // 监听表格编辑事件
      table.on('edit(test)', function(obj){
        var data = obj.data; // 修改后的数据
        var field = obj.field; // 修改的字段名
        var value = obj.value; // 修改后的值

        // 发送Ajax请求保存数据
        // ...

        console.log(data, field, value);
      });
    });
  </script>
</body>
</html>

The code above utilizes the table.render() method from Layui to render a data table, specifying the container #demo and column configuration. In the column configuration, it specifies that the ID, name, age, and email columns are editable. Then, it uses the table.on(‘edit’) method from Layui to listen for table edit events and handle the edited data in the event callback function. It prints out the modified data, the field name that was modified, and the new value in the console.

Note: The URL /api/data in the code above is just an example, you need to replace it with the actual URL of the backend interface. Additionally, you also need to configure other properties of the table according to your own requirements, such as pagination, sorting, etc.

bannerAds