Update datatable info after filtering

Viewed 731

LIVE DATATABLES

The Datatable has two filters for searches:

  1. A regular text input
  2. A Status select

With the first filter, the table works as expected.

The second filter is a select that filters the status (Active or Inactive) without being text-based like the first filter.

The problem is the following:

Let's say I type d in the search input and no status is selected:

enter image description here

I'm getting 4 entries.

This is the text I get:

Showing 1 to 4 of 4 entries (filtered from 7 total entries)

If I select now a status, for example Active, I get 3 results.

enter image description here

This is the text I get:

Showing 1 to 4 of 4 entries (filtered from 7 total entries)

But it should be: Showing 1 to 3 of 3 entries (filtered from 7 total entries)

I think the problem is that I would have to redraw the table after applying the non-text based filter. But I do not know how to do that.

What I've tried (not working, since I am hiding the rows using CSS):

$('#search2').on('change', () => {
  const state = $("#search2").val();
  if (state === "none") {
    $(".status-active").parent().parent().attr("hidden", false);
    $(".status-inactive").parent().parent().attr("hidden", false);
    return;
  }

  $(".status-" + ((state === "active") ? 'inactive' : 'active')).parent().parent().attr("hidden", true);
  $(".status-" + state).parent().parent().attr("hidden", false);
  DT1.search(state).draw();
});

How can I fix this?

1 Answers

Here is what I found

$('#search2').on('change', () => {
    const state = $("#search2").val();
    $.fn.dataTable.ext.search.pop();
    if (state === "none") {
      DT1.draw();
      return;
    }
    $.fn.dataTable.ext.search.push(function(settings, searchData, index, rowData) {
      const $td = DT1.row(index).nodes().to$().find('td');
      return $td.find(`.status-${state}`).length;
    });
    DT1.draw();
  }); 

So to make sure the data is not hidden or removed but only filtered, we should use built-in search method.

$.fn.dataTable.ext.search.pop();

This one is to make sure the data is in unfiltered condition when you are about to filter data.

if (state === "none") {
  DT1.draw();
  return;
}

When you are not filtering, we just have to draw the table and return. Because the previous line we make sure the tables is not filtered at all

$.fn.dataTable.ext.search.push()

Here is what I found in the internet, the solution. I cannot explain this one actually.

const $td = DT1.row(index).nodes().to$().find('td');

This one is to get all the <td> in the table, maybe you can improve this one to find only desired td but this one already works though.

return $td.find(`.status-${state}`).length;

After we find the td tag, we have to make sure that we found the class that we desire. If not found then return 0

DT1.draw();

And then draw the filtered table.

Related