Search code examples
javascriptjquerydatatables

How to get datepicker to show only years on datatables date filter


By using datatables, I am trying to get my two date pickers to let the user only select years, not months or days.

I've tried something like this, but it doesn't seem to work properly:

var minDate, maxDate;

    // Custom filtering function which will search data in column four between two values
    $.fn.dataTable.ext.search.push(
        function (settings, data, dataIndex) {
            var min = minDate.val();
            var max = maxDate.val();
            var date = new Date(data[13]);

            if (
                (min === null && max === null) ||
                (min === null && date <= max) ||
                (min <= date && max === null) ||
                (min <= date && date <= max)
            ) {
                return true;
            }
            return false;
        }
    );

    $(document).ready(function () {
        minDate = new DateTime($('#min'), {
            format: 'YYYY'
        });
        maxDate = new DateTime($('#max'), {
            format: 'YYYY'
        });

        $.noConflict();

        var table = $('.table').DataTable({
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            autoWidth: false,
            ordering: false
        });

        $('#filterDates').on('click', function () {
            table.draw();
        });
    });

Here are my datepickers:

<div>
From: <input type="text" class="form-horizontal" id="min" name="min" />
&nbsp;To: <input type="text" class="form-horizontal" id="max" name="max" />
&nbsp;<button class="btn btn-dark" type="button" id="filterDates">Filter Dates</button>
</div>

Solution

  • Turns out that I need number inputs fields instead of date pickers.

    $.fn.dataTable.ext.search.push(
            function (settings, data, dataIndex) {
                var min = parseInt($('#min').val());
                var max = parseInt($('#max').val());
                var date = parseInt(data[13]) || 0;
    
                if (
                    (isNaN(min) && isNaN(max)) ||
                    (isNaN(min) && date <= max) ||
                    (min <= date && isNaN(max)) ||
                    (min <= date && date <= max)
                ) {
                    return true;
                }
                return false;
            }
        );
    
        $(document).ready(function () {
            $.noConflict();
    
            var table = $('.table').DataTable({
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                autoWidth: false,
                ordering: false
            });
    
            $('#min, #max').on('click', function () {
                table.draw();
            });
        });