Skip to content

Instantly share code, notes, and snippets.

@vctls
Created May 25, 2018 09:06
Show Gist options
  • Save vctls/5a612c56868325beb1cc94656a87ec55 to your computer and use it in GitHub Desktop.
Save vctls/5a612c56868325beb1cc94656a87ec55 to your computer and use it in GitHub Desktop.
Datatables | dynamically created individual column filters
/*===========================*/
/* Individual column filters */
/*===========================*/
var $t = $('#datatable');
var $dt = $t.DataTable();
var $thead = $t.find('thead');
var $tr = $("<tr role='row'></tr>").appendTo($thead);
var $visiCols = $dt.columns(':visible');
// Add headers.
for (var i = 0; i < $visiCols.count(); i++) {
$("<th></th>").appendTo($tr);
}
// Add search inputs on columns with "searchable" class.
$tr.find('th').each(function () {
var $th = $thead.find('th').eq($(this).index());
if ($th.hasClass('searchable')) {
var title = $thead.find('th').eq($(this).index()).text();
$(this).html(
'<input type="text" placeholder="'
+ title
+ '" style="width: 100%;"/>'
);
}
});
// Apply filters.
$tr.find("input").on('keyup change', function () {
$dt
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment