Is it possible to filter a jQuery DataTable by data attribute?
If you want to trigger the filter by code, create a custom filter :
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
var dataLabel = table
.row(dataIndex) //get the row to evaluate
.nodes() //extract the HTML - node() does not support to$
.to$() //get as jQuery object
.find('td[data-label]') //find column with data-label
.data('label'); //get the value of data-label
return dataLabel == 'Active';
}
);
demo -> http://jsfiddle.net/x83zm7qq/
If you just want to be able to use data-label
as the target of filtering when the user types in the searchbox, you can rename data-label
to data-search
or data-filter
:
<td data-search="Active"><i class="fa fa-check fa-lg"></i></td>
dataTables calls it orthogonal data.
you may also define a per-table custom callback by storing it in "settings" in initComplete callback and then invoking in from instance's "settings" object under common search handler. Here's the code:
$(function(){
// the common/unified plugin (for all datatables)
$.fn.DataTable.ext.search.push(
function(settings, columnsOutput, dataIndex, data, outputIndex) {
// this = ext.search array (all custom search functions (including this one)
if (settings._myFilter){
return settings._myFilter.call(settings, {
data: data,
dataIndex: dataIndex,
outputIndex: outputIndex,
columnsOutput: columnsOutput,
settings: settings
});
} else {
return true;
}
}
);
// exact datatable initialization
var dTable = $("#example").DataTable({
// some sample data
data: [{name: "John"}, {name: "Jack"}, {name: "Andy"}],
columns: [{data: 'name'}],
// setting our custom function under the initComplete callback
initComplete: function(settings, json) {
settings._myFilter = function(info){
if ($('#jFilter').prop('checked')){
return (info.data.name.toLowerCase().indexOf('j') >= 0);
} else {
return true;
}
}
}
});
$('#jFilter').on('click', function(){
dTable.draw(); // redraw will apply all the filters
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<link href="https://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" rel="stylesheet"/>
<h2>Click checkbox below to filter by data using a callback</h2>
<label><input id="jFilter" type="checkbox"> J only</label>
<table id="example">
</table>