5

How to add date range filter..

like From-To .

I got working regular search and pagination, etc.. But I dont know how to make date range filter.

I'm using Datatables 1.10.11 version.

My code:

var oTable;

function callFilesTable($sPaginationType, $bPaginate, $bFilter, $iDisplayLength, $fnSortcol, $fnSortdir){

    $.extend($.fn.dataTableExt.oStdClasses, {
        sSortAsc  : 'header headerSortDown',
        sSortDesc : 'header headerSortUp',
        sSortable : 'header'
    }); 

    oTable = $('#sort').DataTable({
        dom : '<"table-controls-top"fl>rt<"table-controls-bottom"ip>',
        pagingType : $sPaginationType,
        paging : $bPaginate,
        searching : $bFilter,
        pageLength : $iDisplayLength,
        order : [ [$fnSortcol, $fnSortdir] ],
        columnDefs : [
            { 
                width      : '50%',
                targets    : [ 2 ],
                orderable  : true,
                searchable : true,
                type       : 'natural'
            },
            { 
                width      : '10%',
                targets   : [ 3 ],
                orderable : true
            },
            { 
                width      : '20%',
                targets   : [ 4 ],
                orderable : true
            },
            { 
                targets    : ['_all'], 
                orderable  : false,
                searchable : false
            }
        ],
        language : paginationTemplate,
        drawCallback : function() {

            checkSelecta();
            placeHolderheight();

            // hide pagination if we have only one page
            var api = this.api();
            var pageinfo = api.page.info();
            var paginateRow = $(this).parent().find('.dataTables_paginate');  

            if (pageinfo.recordsDisplay <= api.page.len()) {
                paginateRow.css('display', 'none');
            } else {
                paginateRow.css('display', 'block');
            }
        }
    });

    oTable.on( 'length.dt', function ( e, settings, len ) {
        updateSession({ iDisplayLength: len });
    });
}

And I'm using NaturalSort 0.7 version.

3
  • there is a range plugin on the datatables site, did you take a look at it? datatables.net/examples/plug-ins/range_filtering.html Commented Jan 2, 2017 at 4:29
  • @Bindrid Yes, but not working. Getting error: Uncaught TypeError: Cannot read property 'substring' of undefined at Array.<anonymous> (range_dates.js:30) Commented Jan 2, 2017 at 4:48
  • I am playing with it. If I get mine working I will post it Commented Jan 2, 2017 at 4:54

2 Answers 2

22

I got mine working base on https://www.datatables.net/examples/plug-ins/range_filtering.html. Here is my jsfiddle https://jsfiddle.net/bindrid/2bkbx2y3/6/

$(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[4]);
            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 });
    var table = $('#example').DataTable();

    // Event listener to the two range filtering inputs to redraw on input
    $('#min, #max').change(function () {
        table.draw();
    });
});
Sign up to request clarification or add additional context in comments.

5 Comments

But in your jsfiddle I changed dates to dd/mm/yyyy and its not working... and also if changing datepicker date format..
updated jsfidddle jsfiddle.net/bindrid/2bkbx2y3/9 If you are using yyyy in jquery datepicker, that is part of the problem. Each y represents 2 places it should be dd/mm/yy.
@Bindrid elegant solution. Thank you. Regarding the dd/mm/yy format, I am not sure why you need the extra code. Javascript Date object works with either format (see jsfiddle.net/2bkbx2y3/123).
The example, as written, requires column number 4 to be a date column. It can be altered to check any column for a valid date then apply the filter to it.
nice buddy. great answer
-1

Following one using momentsjs, the advantage of momentsjs is we can compare different types of date/date time as simple

$.fn.dataTableExt.afnFiltering.push(
        function( settings, data, dataIndex ) {
            var min  = $('#min-date').val()
            var max  = $('#max-date').val()
            var createdAt = data[0] || 0; // Our date column in the table
            //createdAt=createdAt.split(" ");
            var startDate   = moment(min, "DD/MM/YYYY");
            var endDate     = moment(max, "DD/MM/YYYY");
            var diffDate = moment(createdAt, "DD/MM/YYYY");
            //console.log(startDate);
            if (
              (min == "" || max == "") ||
              (diffDate.isBetween(startDate, endDate))


            ) {  return true;  }
            return false;

        }
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.