pee2pee
pee2pee

Reputation: 3802

DataTables change content of cell and make it searchable

I have the following. At the bottom I set the HTML of the cells depending on other values. This works. However when I search the table, rather by the in-built search or using the API (force_table.columns(6).search(val).draw();) it doesn't bring it back

Am I doing this incorrectly?

var force_table = $('#force-table').DataTable({
    "scrollY": 400,
    "scrollX": true,
    "paging": false,
    dom: 'Bfrtip',
    "oSearch": {"bSmart": false},
    buttons: [
        {
            extend: 'excel',
            text: 'Export to Excel',
        }
    ],
    "createdRow": function ( row, data, index ) {
        if ( data[8] > 1) {
            $('td', row).eq(8).addClass('green');
        }
        else {
            $('td', row).eq(8).addClass('orange');
        }
         if ( data[9] > 1) {
            $('td', row).eq(9).addClass('green');
        }
        else {
            $('td', row).eq(9).addClass('orange');
        }
         if ( data[10] > 1) {
            $('td', row).eq(10).addClass('green');
        }
        else {
            $('td', row).eq(10).addClass('orange');
        }

        if ( data[9] > 1 && data[10] > 1) {
            $('td', row).eq(6).html('Yes');
        }
        else {
            $('td', row).eq(6).html('No');
        }
    }
} );

Upvotes: 0

Views: 280

Answers (1)

andrewJames
andrewJames

Reputation: 21918

The createdRow function is good for making DOM-related changes - such as your addClass() examples. But it does not change the data inside the DataTables object. So, even though you can see your change displayed in the table, DataTables is not aware of it - and therefore cannot find it.

An alternative is to move your final if/else logic (for "yes"/"no") into the following:

"columnDefs": [ {
  targets: 6,
  render: function (data, type, row) {
    if ( row[9] > 1 && row[10] > 1 ) {
      return 'yes';
    } else {
      return 'no';
    }
  }
} ]

Instead of using a jQuery selector $('td', row).eq(6).html(...), you are using the DataTables API to manage the table's data. This data can be searched/filtered.

(If you add this new section after your createdRow section, remember to add a comma to separate the sections.)

Upvotes: 1

Related Questions