Returning row data in responsive datatable table

Viewed 9146

I am using the jquery datatable with the responsive option turned on. I am having trouble returning row data when the table is in responsive mode:

My table:

$('#productsTable').DataTable({
        responsive: true
});

The table has a column for product code, brand, category, price, and an 'add to cart' button. The button is supposed to retrieve the row data. However, when the table is in responsive mode (aka it's shrunk and some of the columns have collapsed) and i click my button, it does not return any data.

My html table:

<table id="productsTable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>Product Code</th>
        <th>Brand</th>
        <th>Category</th>
        <th>Price ($)</th>
        <th></th>
    </tr>
</thead>
<tbody>
    {{#each context}}
    <tr>
        <td class="product_code">{{product_code}}</td>
        <td class="brand">{{brand}}</td>
        <td class="category">{{category}}</td>
        <td class="price">{{invoice_price}}</td>
        <td><button type="button" class="btn btn-primary">Add to Cart</button></td>
    </tr>
    {{/each}}
</tbody>
</table>

My add to cart event:

$(".btn-primary").click(function(e) {

    var price = $(this).parent().parent().children('td.price').text();

    var context = {
        product_code: $(this).parent().parent().children('td.product_code').text(),
        brand: $(this).parent().parent().children('td.brand').text(),
        category: $(this).parent().parent().children('td.category').text(),
        price: $(this).parent().parent().children('td.price').text(),
    };

     console.log(context) //console.logs context

});

Image of collapsed table:

Image of collapsed table

Can someone help?

Thanks in advance!

4 Answers

You can define your table and settings.

`var dataTable = $('#tableList').DataTable({
  "serverSide": true,
   .....
});`

Then, use ternary operator to return child data if it exists, otherwise return as normal.

`var rowData = ( $(this).parents('tr').hasClass('child') )
    ? dataTable.row($(this).parents().prev('tr')).data()
    : dataTable.row($(this).parents('tr')).data();`
Related