Skip to content Skip to sidebar Skip to footer

Datatables Sorting Ruined Child Rows

Not sure how I solve this issue, tried 2 days couldn't solve it. I want to prepend using add method but the sorting is running it by sorting hidden row too. The hidden row act as c

Solution 1:

it is happening in this way because you applied sorting on the name column, so datatable being quite smart it adds the row where it needs to be... so if you want to add that in the last remove sorting option on name column...

Here is an updated fiddle which does following things

Here I have added one hidden column with below config

"columnDefs": [{
  "targets": [ 4 ],// Hide 4th column
  "visible": false,
  "searchable": false
}]

You can write anything in format function to have any specific view aswell here I have added a table with 3 rows, but you can customize it

Here I have adding extra rows for every addrows as we have discussed earlier, but here I am adding a row when user clicks on the row, you can see click function how it works..

and here is a small code change:

$(document).ready(function() {
  /* Formatting function for row details - modify as you need */
  function format(d) {
    console.log(d);
    // `d` is the original data object for the row
    return '<table cellpadding="4" cellspacing="0" border="0" style="padding-left:50px;">' +
      '<tr>' +
      '<td>Name:</td>' +
      '<td>' + d[0] + '</td>' +
      '</tr>' +
      '<tr>' +
      '<td>Full Name:</td>' +
      '<td>' + d[4] + '</td>' +
      '</tr>' +
      '<tr>' +
      '<td>Extra info:</td>' +
      '<td>And any further details here (images etc)...</td>' +
      '</tr>' +
      '</table>';
  }

  var table = $('#example').DataTable({
    "columnDefs": [{
        "targets": [4],
        "visible": false,
        "searchable": false
      }]
      /* the problem is here, it won't work if I enable sorting*/
  });

  function appendRow() {
    var t = $('#example').DataTable();

    var node = t.row.add([
      "James Bond",
      "Spy", "55", "$9000", "James Bond Larry"
    ]).draw().node();

    console.log(node);
    $(node).addClass('result-row').hide().fadeIn('normal');
  };

  $('#add').click(function() {
    appendRow();
  });

  $('#example tbody').on('click', '.result-row', function() {
    var tr = $(this).closest('tr');
    var row = table.row(tr);

    if (row.child.isShown()) {
      // This row is already open - close it
      row.child.hide();
      tr.removeClass('shown');
    } else {
      // Open this row
      row.child(format(row.data())).show();
      tr.addClass('shown');
    }
  });
});

reference 1 - sort

reference 2 - row.add

referece 3 - Adding row on click


Post a Comment for "Datatables Sorting Ruined Child Rows"