DataTable Select in Header
How to put the select option in the second header row?
And how to sync it with the select located at the footer?
by Carl Angelo Nievarez
HTML
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.9/js/dataTables.fixedHeader.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/fixedheader/3.1.9/css/fixedHeader.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/fixedheader/3.1.9/css/fixedHeader.dataTables.min.css" rel="stylesheet"/>
<table class="table table-bordered responsive nowrap" id="example" width="100%">
<thead>
<tr>
<th width="3%">No</th>
<th width="30%">Machine</th>
<th width="15%">Spec1</th>
<th width="15%">Spec2</th>
<th width="6%">Spec3</th>
<th width="6%">Spec4</th>
<th width="6%">Spec5</th>
<th width="6%">Spec6</th>
<th width="6%">Qty</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th width="3%">No</th>
<th width="30%">Machine</th>
<th width="15%">Spec1</th>
<th width="15%">Spec2</th>
<th width="6%">Spec3</th>
<th width="6%">Spec4</th>
<th width="6%">Spec5</th>
<th width="6%">Spec6</th>
<th width="6%">Qty</th>
<th></th>
</tr>
</tfoot>
</table>
JavaScript
$("#example tfoot th").each(function() {
var title = $(this).text();
$(this).html('<input class="form-control" type="text" placeholder="Search ' + title + '" style="width:100%" />');
});
$("#example thead tr").clone(true).appendTo( "#example thead" );
$("#example thead tr:eq(1) th").each( function (i) {
var title = $(this).text();
$(this).html( '<input class="form-control" type="text" placeholder="Search '+title+'" style="width:100%" />' );
$( "input", this ).on( "keyup change", function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
// DataTable
var table = $('#example').DataTable({
"columnDefs": [{
"targets": [0, 6],
"orderable": false,
}, ],
"responsive": true,
"orderCellsTop": true,
"fixedHeader": true
});
// Apply the search
table.columns().every(function() {
var that = this;
$('input', this.footer()).on('keyup change', function() {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
//Header
table.column(1).every(function() {
var column = this;
var select = $('<select class="form-control" style="width:100%"><option value=""></option></select>')
.appendTo($(column.header()).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>')
});
});
table.column(2).every(function() {
var column = this;
var select = $('<select class="form-control" style="width:100%"><option...