'Datatables, initComplete - select on header, not footer
I have this code:
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select style="width: 100%;"><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
This is a test of what I'm doing: Here I'm testing on how to do it https://jsfiddle.net/pmiranda/nrzpq5g2/
What I'm trying is to append the filters of each column on top, not in the footer. If I set .appendTo($(column.header()).empty())
I can have the filter on top but I lose my actual header:
https://jsfiddle.net/pmiranda/y1s6auj4/
Any idea?
Solution 1:[1]
I guess you want this. When you appended the select, you cleared the contents with
.appendTo( $(column.header()).empty() )
You just needed to avoid that action:
.appendTo( $(column.header()) )
EDIT after comment:
To avoid triggering the sorting, you can prevent the propagation of the click (like here)
.on( 'click' , function (evt){
evt.stopPropagation();
})
Solution 2:[2]
What I did was this:
//.appendTo($(column.footer()).empty())
.appendTo( $("#table-tracking thead tr:eq(1) th").eq(column.index()).empty() )
But of course I need two tr
in thead
, and also put this option on datatable instance:
orderCellsTop: true,
Solution 3:[3]
I first clone the headers, and then replace them with the select ones,
$(document).ready(function () {
$('#dashboard thead tr')
.clone(true)
.addClass('filters')
.appendTo('#dashboard thead');
var table = $('#dashboard').DataTable({
"responsive": true,
"autoWidth": false,
"paging": false,
"searching": true,
"order": [[ 0, "desc" ]],
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
//For each column
api.columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
//.appendTo( $(column.header()) )
.appendTo( $(".filters th").eq(column.index()).empty() )
.on( 'click' , function (evt){
evt.stopPropagation();
})
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | pmiranda |
Solution 3 | Yamiel Serrano |