Star089 Star089 - 5 months ago 61
jQuery Question

Hiding rows with class "hidden" after change the checkbox

I'm using jQuery datatables. I'd like to hide all rows with

class="hidden"
.

This code:

var table = $('#table1').DataTable();
table.rows('.hidden').hide();


It's not working (rows are not hidden), and I see this text in console:


table.rows(...).hide is not a function


How can I use
class="hidden"
to hide all rows?




HTML code:

<tr class="">
<td>1</td>
<td>ABC</td>
<td>17</td>
</tr>

<tr class="hidden">
<td>2</td>
<td>DEF</td>
<td>22</td>
</tr>

<tr class="">
<td>3</td>
<td>GHI</td>
<td>55</td>
</tr>

<tr class="hidden">
<td>4</td>
<td>JKL</td>
<td>11</td>
</tr>
<input id="hideRows" name="hideRows" type="checkbox">


JS code:

$('#table1').DataTable();

$('#hideRows').change(function()
{
var table = $('#table1').DataTable();
$('tr.hidden').hide();
$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
if ($(oSettings.nTable).hasClass('hidden')) {
return aData[16] == '' || $('#hideRows').is(':checked');
} else return true;
});
table.draw();
});

Answer

The following solutions assume that the rows have already been marked with the hidden class.

To use DataTable filtering to hide the rows, implement a filter function, like this:

$.fn.dataTable.ext.search.push(
   function(settings, data, dataIndex) {
      return $(table.row(dataIndex).node()).hasClass('hidden');
   }
);

While it's not recommended, you can use jQuery to hide the rows, but there are gotchas. (There are valid reasons that you may need to do this, but they will not be covered here.) Simply query the hidden class of the HTML tr elements using a regular jQuery selector, and then apply .hide(), like this:

$('tr.hidden').hide();

If you use non-filter functions to hide the rows (either using the jQuery method above, or with CSS styling on the hidden class), there may be side effects. See jQuery DataTable - Hide rows the intended way for additional information. If you display / filtering issues, you'll have to let DataTables know which rows have already been hidden:

$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
    if ($(oSettings.nTable).hasClass('hidden')) {
        return aData[16] == '' || $('#chkShowExcluded').is(':checked');
    } else return true;
});

Note that after using any of these methods, you may have to force a redraw after applying the hidden classes to the table rows, like this:

table.draw();
Comments