I am new with the DataTable plugin and i am trying to create a data-range filter for my project and for that i tried to adapt the code used on this answer https://stackoverflow.com/a/41422122/11095976.
On a test example, i manage to put it to work but when im adapting it to my code it doesnt seem to work.
Besides nothing happening, it gives me no errors on the console.
This is what i have tried :
$(document).ready(function() {
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#min').datepicker('getDate');
var max = $('#max').datepicker('getDate');
var startDate = new Date(data[1]);
if (min == null && max == null) return true;
if (min == null && startDate <= max) return true;
if (max == null && startDate >= min) return true;
if (startDate <= max && startDate >= min) return true;
return false;
}
);
$('#min').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
$('#max').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
$('#tabela thead tr').clone(true).appendTo( '#tabela thead' );
$('#tabela thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
var table = $('#tabela').DataTable( {
orderCellsTop: true,
responsive: true,
fixedHeader: true,
dom: 'Bfrtip',
buttons: ['csv', 'excel', 'pdf' ],
initComplete: function () {
this.api().columns('.filtro').every( function () {
var column = this;
var select = $('<select><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>' )
} );
} );
}
} );
$('#min, #max').change(function () {
table.draw();
});
} );
My HTML:
<table border="0" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>Minimum age:</td>
<td><input type="text" id="min" name="min"></td>
</tr>
<tr>
<td>Maximum age:</td>
<td><input type="text" id="max" name="max"></td>
</tr>
</tbody></table>
<div class="table-responsive">
<table id="tabela" class="table table-bordered table-striped">
<thead>
<tr>
<th class="filtro">Trabalhador</th>
<th>Marcação</th>
<th class="filtro">Local</th>
<th class="filtro">Departamento</th>
</tr>
</thead>
<tbody id="myTable">
<?php foreach ($lista as $key => $value) { ?>
<tr>
<td><?= $value['Colaborador'] ?></td>
<td><?= $value['Marcacao'] ?></td>
<td><?= $value['Local'] ?></td>
<td class="dep"><?= $value['Departamento'] ?></td>
</tr>
<?php } ?>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</tbody>
</table>