I have multiple tables in my page with class="example" . I have applied individual column searching on my tables using the following code :
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('.example tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />');
} );
// DataTable
$('.example').each(function(){
var table = $(this).DataTable();
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that.search( this.value ).draw();
}
});
});
});
$('.example tfoot th').appendTo('.example thead'); //Problem
} );
By default, the individual search column inputs are added to the bottom of the tables. Now, The line with the comment (//Problem) is what I am using to add the individual search column inputs at the top of each table. But this adds the individual search column inputs of the first table to all the other tables. I think this can be solved by placing the line (//Problem) inside this loop :
$('.example').each(function()
But I am not able to figure this out how do I use it inside. I tried many things but that didn't work for me.
To get the functionality you want.
You need to change the jQuery code so that the search boxes are created in the header of the table instead of the footer.
With the current code, there are two lines the specify the work is to be done on the <tfoot>
HTML tag.
Line 3: $('.example tfoot th').each( function () {
Line 13: $( 'input', this.footer() ).on( 'keyup change', function () {
Simply change these line to reflect that you would like this to take place in the <thead>
instead.
$(document).ready(function() {
// Setup - add a text input to each HEADER cell
$('.example thead th').each( function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('.example').DataTable();
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.header() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that.search( this.value ).draw();
}
} );
} );
} );
Codepen example: https://codepen.io/selabie68/pen/gErWbL