Filtering DataTable rows by data-attribute

Filtering DataTable rows by data-attribute

tdevine33tdevine33 Posts: 4Questions: 3Answers: 0

I am working on a data table using DataTable.js and need to create filtering to limit a row based on a data-attribute. I have an attribute of data-active set on the <tr>. Currently in my testing I have 6 rows, 2 inactive and 4 active - like so.

<tr class="funder funder--inactive" data-active="false">...1...</tr>
<tr class="funder funder--active" data-active="true">...2...</tr>
<tr class="funder funder--active" data-active="true">...3...</tr>
<tr class="funder funder--active" data-active="true">...4...</tr>
<tr class="funder funder--inactive" data-active="false">...5...</tr>
<tr class="funder funder--active" data-active="true">...6...</tr>

Then in the DataTable search, I added a function to hide any row based on the data-active attribute.

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex, rowObj, counter) {
    var el = settings.aoData[counter].nTr,
        isActive = $(el).data('active');

    return isActive;
});

And lastly I build the table using DataTable.js

var $fundersTable = $('#fundersList').DataTable({ ... });

The table is then filtered down to 4 rows, but instead of being the rows with data-active="true" it only filters the first 2 rows - leaving the following rows.

<tr class="funder funder--active" data-active="true">...3...</tr>
<tr class="funder funder--active" data-active="true">...4...</tr>
<tr class="funder funder--inactive" data-active="false">...5...</tr>
<tr class="funder funder--active" data-active="true">...6...</tr>

Is there something I'm missing on specifying the row index on which item to limit? All the example in their docs seem to just return true or false per row as I've done here.

Any help is greatly appreciated, thanks!

Answers

  • kthorngrenkthorngren Posts: 21,262Questions: 26Answers: 4,934

    I believe the search plugin will iterate the rows in the order they are displayed in the table. Using the counter parameter will access the wrong array element in aoData. Use dataIndex instead which is the same as the row().index() and should access the proper row element. See the Search Plugin docs for more details.

    Kevin

  • kthorngrenkthorngren Posts: 21,262Questions: 26Answers: 4,934
    edited November 2021

    You may want to consider using the API to access the data instead of directly accessing the settings object which is considered private. The settings object likely won't change but using the API will protect your code if it does. Here is an updated example using the API:
    http://live.datatables.net/pibepaje/1/edit

    Kevin

Sign In or Register to comment.