【问题标题】:How to Get Data from checkbox selected row in dataTables如何从dataTables中的复选框选定行中获取数据
【发布时间】:2017-04-15 06:26:35
【问题描述】:

我正在使用这个data table

我需要从所选行中同时获取 ProductIDProductStatus,其中 ProductID 嵌入在每一行的 TR ID 中。

我没有在表格中显示 productStatus。但是我需要在选择行时获取状态。我在哪里可以添加它们?

请指导我....

代码

function loadClick() {

  const databaseRef = firebase.database().ref('S01/Products');
  var query = databaseRef.orderByKey().startAt("C09M03S03").endAt("C09M03S04").limitToFirst(6);

  query.once("value")
    .then(function (snapshot) {
      snapshot.forEach(function (childSnapshot) {

        var t = $('#products_table').DataTable();

        var key = childSnapshot.key;

        var MID = childSnapshot.child("productMID").val();
        var SID = childSnapshot.child("productSID").val();
        var ProductID = childSnapshot.child("productID").val();
        var name = childSnapshot.child("productName").val();
        var unit = childSnapshot.child("productUnit").val();
        var productMRP = childSnapshot.child("productMRP").val();
        var price = childSnapshot.child("productSellingPrice").val();
        var buying_price = childSnapshot.child("productBuyingPrice").val();
        var productstatus = childSnapshot.child("productStatus").val();

        var row = "";

        t.row.add(['<td class="cell-60 responsive-hide"></td><td class="cell-300"><a class="avatar" href="javascript:void(0)"><img class="img-responsive" src="../../../global/portraits/1.jpg"alt="..."></a></td>', '<td>' + name + '</td>',
        '<td>' + unit + '</td>', '<td tabindex="1">' + productMRP + '</td>', '<td tabindex="2">' + price + '<\/td>',
        '<td tabindex="3">' + buying_price + '<\/td>']).node().id = ProductID;
        t.draw(false);

      });
    });
}

function EditProdStatus(ProductID, ProductStatus) {
  var statusRef = firebase.database().ref('S01/Products').child(ProductID).child("productStatus");
  statusRef.set(!ProductStatus);
  console.log("Product Status changed to " + ProductStatus);
}

$(document).ready(function () {
  loadClick();
  var table = $('#products_table').DataTable({
    'columnDefs': [{
      orderable: false,
      className: 'select-checkbox',
      targets: 0
    },
    {
      'targets': 3,
      'createdCell': function (td, cellData, rowData, row, col) {
        $(td).attr('tabindex', '1');
      }
    },
    {
      'targets': 4,
      'createdCell': function (td, cellData, rowData, row, col) {
        $(td).attr('tabindex', '2');
      }
    },
    {
      'targets': 5,
      'createdCell': function (td, cellData, rowData, row, col) {
        $(td).attr('tabindex', '3');
      }
    }
    ],
    select: {
      style: 'os',
      selector: 'td:first-child'
    },
    order: [[1, 'asc']]
  });

});

function productDisable() {

  var oTable = $('#products_table').dataTable();
  $(".select-checkbox:checked", oTable.fnGetNodes()).each(function () {
    console.log($(this).val());
  });
}

HTML

   <table id="products_table" class="table is-indent tablesaw" cellspacing="0" width="100%">
                      <thead>
                            <tr>
                                  <th class="pre-cell"></th>
                                  <th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="3">Product Name</th>
                                  <th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product Unit</th>
                                  <th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product MRP</th>
                                  <th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Selling Price</th>
                                  <th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Buying Price</th>
                            </tr>
                      </thead>
                </table>

jsFiddle Demo

【问题讨论】:

  • product status 列的索引值是多少?
  • 我不想在表格中显示状态。但我需要它发送到函数

标签: javascript jquery datatables datatables-1.10


【解决方案1】:

对于那些您不想在 DataTable 中显示的td,您只需在您的columnDefs 中提供Visible:false。它们将被隐藏,但如果它们在选定的行中,您可以检索它们的数据。

$('#example').DataTable({
    columnDefs: [{
      orderable: false,
      className: 'select-checkbox',
      targets: 0
    }, {
      "targets": [2],
      "visible": false,
      "searchable": false
    }]
})

另一件事是您正在使用fnGetNodes,它是datatable v1.9 在选择时的旧功能,不适用于DataTable 10.1。您可以按如下方式获取选定的行:

table.rows('.selected').data();

即使您在不同页面中选择了多行,这也会返回 selected rows

您可以找到 Demo here

正如您在演示中看到的,对于员工数据,他们的 position 列在 DataTable 中不可见,但其数据在检索选定行的数据时可用。

Documentation here for Hidden columns


更新

我已经更新了你的 Fiddle。 Updated Fiddle .

【讨论】:

  • 成功了。但我无法检索产品状态和产品 ID ?
  • @user3467240 在您的表格 html 中,您没有 ProductID 和 ProductStatus 列。
  • t.row.add([....] 中,您不会为ProductIdProductStatus 添加值。
  • 我将 ProductID 添加为每一行的 TR ID。我已将 productStatus 添加为我的第二列并将可见设置为 false。为简单起见,我需要获取所选行的 TR ID 和第二列的值。
【解决方案2】:

试试这个,对你有帮助

var table = $('#example').DataTable();
 
$('#example tbody').on( 'click', '.checkbox', function () {
if(this.checked==true)
{
console.log( table.row( this.closest('tr') ).data() );
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/js/jquery.dataTables.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>check</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    
    <tbody>
        <tr>
            <td><input type="checkbox" class="checkbox" ></td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="checkbox" ></td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
    </tbody>
</table>

【讨论】:

    【解决方案3】:

    试试这个...

    将您的 productStatus 列添加到 HTML 中:

    '<td>' + productStatus + '</td>'
    

    假设它位于第 8 列索引处。所以将以下内容添加到 dataTables columnDefs 中:

    {
        'targets': 8,
        'visible': false,
    }
    

    现在,在productDisable(),您可以从每个选定的行中获取 productID 和 productStatus,如下所示:

    function productDisable() {
        table.rows(".selected").every(function() {
            var row = this.node();
            var productID = row.id;
            var productStatus = this.data()[8]; 
            console.log(productID, productStatus);
            // do whatever with productID and productStatus
        });
    }
    

    Demo

    【讨论】:

    • 如果你能在jsFiddle或者codePen中发布一个live demo,我看看能不能调试一下。
    • jsFiddle - jsfiddle.net/ArulNadhaN/vjqj7eg5/1
    • 抱歉,这根本不适合我。在开始调试实际问题之前,我需要至少部分工作。
    • 没关系,我设法让一些东西在本地文件中工作。请参阅编辑后的答案。
    【解决方案4】:

    我使用 Datatable 1.10,此代码对我有用 “btnSubmit”是按钮的 ID,当您单击按钮选中的复选框数据时,您将获得

       // Handle form submission event 
       $('#btnSubmit').on('click', function() {
           //Hold the Object Data what are the checkbox selected
           var tblData = table.api().rows('.selected').data();
           var tmpData;
           //Iterate the Object and extract you one one by one row data With Hidden Id Also
              $.each(tblData, function(i, val) {
                tmpData = tblData[i];
                alert(tmpData);
              }); 
        })
    

    【讨论】:

      【解决方案5】:
      //You can use this one.
      $( $('#example').DataTable().$('.checked').map(function () 
      {
          return $(this).closest('tr');
          //want to get attribute
          //var id = $(this).closest('tr').find('td.Select').attr('id');
      }));
      

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 2021-10-07
        • 2017-07-28
        • 2019-03-23
        • 2014-08-16
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 2014-04-05
        相关资源
        最近更新 更多