I have a table with multiple columns, each column has an input field to search through a particular column.
But for 4 columns, which are number-based, I wanted a range filter. That means, those 4 columns will have two input fields, the first is to put the minimum range number and the second is to put the maximum range number. Take a look at the reference image(it has only 2 columns out of 4 number-based columns, the other 2 are not visible in the screenshot).
Now I am trying to implement this functionality by adding my own search function to the datatable search function array, as given in the docs. https://datatables.net/examples/plug-ins/range_filtering.html
But the search is not working, or i say it is not making any changes in UI at all.
this is the code -
// Call the dataTables jQuery plugin
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#dataTable thead tr').clone(true).appendTo('#dataTable thead');
$('#dataTable thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
if(title==='clicks' || title==='impressions' || title==='ctr' || title==='position') {
$(this).html(`
<div class='d-flex'>
<input name=${title}_min id=${title}_min class='' type='number' min='0' placeholder='Min' style='width: 80px;'/>
<input name=${title}_max id=${title}_max class='ml-1' type='number' min='0' placeholder='Max' style='width: 80px;'/>
</div>
`);
var minInputValue = parseFloat($(`input[id=${title}_min]`, this).val()) || 0;
var maxInputValue = parseFloat($(`input[id=${title}_max]`, this).val()) || 0;
$.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
// logic to filter min and max values
var colVal = parseFloat(data[i]) || 0;
if (colVal >= minInputValue || colVal <= maxInputValue || minInputValue === 0 || maxInputValue === 0) {
return true;
}
return false;
});
$(`#${title}_min`, this).on('keyup change', function () {
minInputValue = parseFloat($(this).val()) || 0;
console.log('min', minInputValue);
dataTable.draw();
});
$(`#${title}_max`, this).on('keyup change', function () {
maxInputValue = parseFloat($(this).val()) || 0;
console.log('max', maxInputValue);
dataTable.draw();
});
} else {
$(this).html('<input type="text" placeholder="Search '+title+'" />');
$('input', this).on('keyup change', function () {
if (dataTable.column(i).search() !== this.value) {
dataTable.column(i).search(this.value).draw();
}
});
}
});
var dataTable = $('#dataTable').DataTable({
orderCellsTop: true,
paging: true,
scrollX: 400,
searching: true,
// lengthMenu: true,
dom: 'Blfrtip',
buttons: [
{ extend: 'csv', className: 'mb-2 btn btn-sm btn-info'},
{ extend: 'excel', className: 'mb-2 btn btn-sm btn-info' },
{ extend: 'pdf', className: 'mb-2 btn btn-sm btn-info' },
{ extend: 'print', className: 'mb-2 btn btn-sm btn-info' },
]
});
$('#dataTable_wrapper .dataTables_length').css({ display: 'inline-flex', 'margin-left': '20px' })
});
I really appreciate your help.