Reputation: 280
I just want to filter my datatable when a user selects a date between two datepicker. I have tried a code but it doesn't show when I select a date. Anyone knows how do I fix my code? Thanks so much!
This what I've tried:
function implement_cm_table() {
var table = $('#show-cm-table').DataTable({
autoWidth: false,
responsive: true,
dom: '<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"ip>',
language: {
search: '<span>Search</span> _INPUT_',
lengthMenu: '<span>Show:</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': '→', 'previous': '←' }
}
});
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#from').datepicker('getDate');
var max = $('#to').datepicker('getDate');
var startDate = new Date(data[0]);
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 });
// Event listener to the two range filtering inputs to redraw on input
$('#min, #max').change(function () {
table.draw();
});
}
Upvotes: 1
Views: 723
Reputation: 21917
You can make the following changes to your code:
<script type="text/javascript">
$(document).ready(function() {
implement_cm_table();
} );
</script>
min
and max
selector names to from
and to
, here: $('#from').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
$('#to').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
// Event listener to the two range filtering inputs to redraw on input
$('#from, #to').change(function () {
table.draw();
});
<script type="text/javascript">
$('#from').datepicker({ dateFormat: 'yy-mm-dd' });
$('#to').datepicker({ dateFormat: 'yy-mm-dd' });
</script>
...and instead add those date formatters to the other datepicker
declarations, towards the botton of your script:
$('#from').datepicker({ dateFormat: 'yy-mm-dd', onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
$('#to').datepicker({ dateFormat: 'yy-mm-dd', onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
After I made these changes to my version of your code, the filtering started working correctly.
Basically, the document ready function is needed to ensure the page is ready for DataTables to be initialized. And then you need to fix the incorrect date picker selectors and make sure each selector is only declared one time.
Upvotes: 1