Banana Banana - 3 years ago 180
jQuery Question

Apply datatables filtering to only one table

I'm using custom filtering per class name. I also have two different dataTables on my page, but it seems that the filter I'm adding applies to both dataTables. I would like to specify on which one it actually applies to.

$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
var myRowClasses = oSettings.aoData[iDataIndex].nTr.className.split(" ");
if($("#subplayers").is(":checked")) {
return myRowClasses.indexOf('insub') > -1;
} else {
return myRowClasses.indexOf('allplayers') > -1;
}
});


This filter applies to both tables (table 1 with it
tabledata
and table 2 with id
tabledata2
). How can I modify this code in order for it to work only on table 1?

Table code:

var table = $('#tabledata').DataTable({
'fnCreatedRow': function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'col' + iDataIndex+'_filter');
if (initatedTable){
$(nRow).addClass("insub");
$(nRow).addClass("allplayers");
}
}
});

var table2 = $('#tabledata2').DataTable({
'fnCreatedRow': function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'col' + iDataIndex+'_filter');
}
});

Answer Source

You need to add an if check to your filter function like this;

$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
  if (settings.nTable.id === 'tabledata') {
     // filter example
  }
  else {
    // ...
  }        
});

in this example, if (settings.nTable.id === 'tabledata') line will do the trick.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download