Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DataTable filtering - so confusing

Tags:

datatables

I am new to the jQuery dataTables plugin found on https://datatables.net/

I am trying to implement a custom filter for the table:

Basically, when I click a button, a custom filtering function will test the value of column #1 (numeric value) for all rows, and if the value in the column < 50 for a row, the row stays, otherwise the row is hidden.

The concept should be very simple, but I can't seem to find the right way to use the API:

  • column.filter() returns an array of column value
  • column.search() can only accept text data (not function)

What's the API that can achieve the effect?

Is there anything like the following?

var api = $('#table').DataTable();

api.column(1).data().somefilterfunction(function (val, ind) {
    return parseFloat(val) < 50;
}).draw();
like image 261
SamuelC Avatar asked Jun 27 '26 12:06

SamuelC


1 Answers

Have you seen this article in the documentation -> https://datatables.net/examples/plug-ins/range_filtering.html ??

You can create a custom filtering function on-the-fly, triggered by a button :

<button id="filter">filter < 50</button>

script :

$("#filter").click(function() {
    $.fn.dataTable.ext.search.push(
        function( settings, data, dataIndex ) {
            return parseFloat(data[0])<50
                ? true
                : false
        }     
    );
    table.draw();
    $.fn.dataTable.ext.search.pop();
});

demo -> http://jsfiddle.net/dpwgqs2o/

Notice that the filter is created inside the click handler itself, and removed again as soon the table is drawn. This makes the filter temporary, i.e when the user click on a column header, the filter is cleared. If you want a permanent filter, make the filter global and do not remove it.

like image 163
davidkonrad Avatar answered Jun 30 '26 12:06

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!