jQuery DataTable filtering - so confusing

2019-01-28 13:47发布

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();

标签: datatables
1条回答
smile是对你的礼貌
2楼-- · 2019-01-28 14:11

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.

查看更多
登录 后发表回答