【问题标题】:How to get data from a selected data from the DataTables如何从 DataTables 中的选定数据中获取数据
【发布时间】:2021-10-20 00:21:24
【问题描述】:

我正在尝试从 DataTable 中获取选定的数据,但我无法检索数据,但是我能够检索行索引号。任何人都可以帮助我获取选定的行数据。我将提供一个工作小提琴以便于工作。

$(document).ready(function() {
   var table = $('#example').DataTable({
      'ajax': 'https://gyrocode.github.io/files/jquery-datatables/arrays_id.json',
      'columnDefs': [
         {
            'targets': 0,
            'checkboxes': {
               'selectRow': true
            }
         }
      ],
      'select': {
         'style': 'multi'
      },
      'order': [[1, 'asc']]
   });
   
   // Handle form submission event 
   $('#frm-example').on('submit', function(e){
      var form = this;
      
      var rows_selected = table.column(0).checkboxes.selected();

      // Iterate over all selected checkboxes
      $.each(rows_selected, function(index, rowId){
         // Create a hidden element 
         $(form).append(
             $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'id[]')
                .val(rowId)
         );
      });

      // FOR DEMONSTRATION ONLY
      // The code below is not needed in production
      
      // Output form data to a console     
      $('#example-console-rows').text(rows_selected.join(","));
      
      // Output form data to a console     
      $('#example-console-form').text($(form).serialize());
       
      // Remove added elements
      $('input[name="id\[\]"]', form).remove();
       
      // Prevent actual form submission
      e.preventDefault();
   });   
});

https://jsfiddle.net/cvinhar/82csLoy5/

【问题讨论】:

  • 嗨。什么时候获取选中的数据?如何?当您选中该框和提交按钮时?提交时所选行的数据?请用例子解释一下,我很乐意看看:)
  • 嗨。当我们勾选复选框并单击提交时,我想获取名称和位置数据而不是 rowId。

标签: javascript html jquery datatable datatables


【解决方案1】:

您可以在提交时简单地使用:

let selectedValues = table.rows( { selected: true } ).data();

然后循环遍历你的值。

【讨论】:

  • 这是一个很好的解决方案。我想添加一个注释,需要加载选择扩展才能使其工作。附加信息:datatables.net/extensions/select
  • 您好,请问如何循环获取数据?
  • @Harvin Chandran 当然可以,但是为什么循环遍历数组会出现问题?
  • 你已经在你的代码中使用你的 $.each 来做这件事,困难的部分是获取数据......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 2018-02-11
  • 1970-01-01
  • 2016-05-14
相关资源
最近更新 更多