How to add custom search by date range in jQuery DataTables?
How to add custom search by date range in jQuery DataTables?
Asked here http://stackoverflow.com/questions/31580831/how-to-add-custom-search-by-date-range-in-jquery-datatables but no answer.
I use DataTables 1.10.6 (https://datatables.net/) on ASP.NET MVC project.
There I have table with variable columns count (depends on table, defined on load). For some columns I have simple text search, for other - drop-down values search. And for one column (with dates) I need to provide date range search. I try this solution https://datatables.net/examples/plug-ins/range_filtering.html but it runs after table initialization (for every table and for same column with index 3) while I need it only when value in input field is changed.
I try this code (from example):
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var min = parseInt( $('#min').val(), 10 );
var max = parseInt( $('#max').val(), 10 );
var age = parseFloat( data[3] ) || 0; // use data for the age column
if ( ( isNaN( min ) && isNaN( max ) ) ||
( isNaN( min ) && age <= max ) ||
( min <= age && isNaN( max ) ) ||
( min <= age && age <= max ) )
{
return true;
}
return false;
}
);
But this code does not depends on table and when I have two tables on same page I don't know how to take input value from current table. I need custom search function that can take min/max values, column index (where to search) and works per table.
I need something like this:
function DatarangeColumnCustomSearch(searchQuery) {
if (searchQuery != undefined) {
var startDate = Date.parse(searchQuery[0]),
endDate = Date.parse(searchQuery[1]),
comparativeDate = Date.parse(rowData[*...current column...*]);
if (startDate <= comparativeDate && comparativeDate < endDate.addDays(1)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
table.api().columns('.whereSearchForDaterange').every(function() {
var column = this;
$('input.datarangeFilter', this.footer()).on('keyup change', function () {
var dates = this.value.split(' - ');
column.DatarangeColumnCustomSearch(dates).draw();
});
});
Please, help!
Answers
You also can use my yadcf plugin for datatables, it got 10 filter types and two different date pickers (jQuery UI Datepicker / Bootstrap 3 Datepicker) see yadcf showcase
Thanks, daniel_r! I will try.
But question is still interesting for me.