How can you retrieve the selected data in a table using layui?

In layui, you can retrieve the selected data in a table by listening to the change event of the checkbox selection box. The specific steps are as follows:

  1. Add a “lay-filter” attribute to the checkbox in the table to identify the name of the checkbox, for example lay-filter=”check”.
  2. In JavaScript code, use the form module from layui to listen to the change event of a checkbox.
  3. In the callback function of the change event, you can use the checkStatus method of the layui table module to retrieve the selected data in the table.

Here is an example code:

HTML code:

<table class="layui-table">
  <thead>
    <tr>
      <th><input type="checkbox" lay-filter="check" /></th>
      <th>姓名</th>
      <th>年龄</th>
      <th>性别</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" lay-filter="check" /></td>
      <td>张三</td>
      <td>20</td>
      <td></td>
    </tr>
    <tr>
      <td><input type="checkbox" lay-filter="check" /></td>
      <td>李四</td>
      <td>22</td>
      <td></td>
    </tr>
  </tbody>
</table>

JavaScript code:

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

  // 监听checkbox选择框的change事件
  form.on('checkbox(check)', function(data) {
    // 获取表格选中的数据
    var checkStatus = table.checkStatus('tableId');  // tableId为表格的id
    var data = checkStatus.data;  // 获取选中的数据
    console.log(data);
  });
});

In the code above, the change event callback function is triggered when the status of the checkbox changes. Within the callback function, the table.checkStatus method is used to retrieve the selected data from the table and output it to the console.

bannerAds