Created
May 25, 2018 09:06
-
-
Save vctls/5a612c56868325beb1cc94656a87ec55 to your computer and use it in GitHub Desktop.
Datatables | dynamically created individual column filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*===========================*/ | |
/* 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