in

Datatable Custom Date Range Filter


happy new year! This is my 2nd question here. Hehehe.

I have this data table and the filtering date ranges are not working. Also when filtering the dropdown for “active” and “inactive”, it’s filtering data for “inactive” but when “active” is selected, it’s still showing the “inactive” data.

This is the link of the template that I used https://preview.keenthemes.com/keen/demo1/features/datatables/search-options/column-search.html

Here is my javascript code:

    <script type="text/javascript">

"use strict";
var KTDatatablesSearchOptionsColumnSearch = function() {

$.fn.dataTable.Api.register('column().title()', function() {
    return $(this.header()).text().trim();
});

var initTable1 = function() {

    // begin table
    var table = $('#allcustomers_datatable').DataTable({
        responsive: true,    
        ajax: {
            url: '/User/CustomerList',
            type: 'GET',
            dataSrc: 'response'
        },
        columns: [{
                data: 'userId'
            },
            {
                data: 'name'
            },
            {
                data: 'email'
            },
            {
                data: 'phoneNumber'
            },
            {
                data: 'registerType'
            },
            {
                data: 'dateRegistered',
            },
            {
                data: 'isActive'
            },
            {
                data: 'userId',
                responsivePriority: -1
            },
        ],
        initComplete: function() {
            var thisTable = this;
            var rowFilter = $('<tr class="filter"></tr>').appendTo($(table.table().header()));

            this.api().columns().every(function() {
                var column = this;
                var input;

                switch (column.title()) {
                    case 'ID':
                    case 'Customer Name':
                    case 'Email Address':
                    case 'Phone Number':
                        input = $(`<input type="text" class="form-control form-control-sm form-filter datatable-input" data-col-index="` + column.index() + `"/>`);
                        break;

                    case 'Register Type':
                        var status = {
                            1: {
                                'title': 'Email',
                                'class': 'label-light-primary'
                            },
                            2: {
                                'title': 'Facebook',
                                'class': 'label-light-danger'
                            },
                            3: {
                                'title': 'Google',
                                'class': 'label-light-primary'
                            },
                            4: {
                                'title': 'Apple',
                                'class': 'label-light-success'
                            },
                        };
                        input = $(`<select class="form-control form-control-sm form-filter datatable-input" title="Select" data-col-index="` + column.index() + `">
                                    <option value="">Select</option></select>`);
                        column.data().unique().sort().each(function(d, j) {
                            $(input).append('<option value="' + d + '">' + status[d].title + '</option>');
                        });
                        break;

                    case 'Date Registered':
                        input = $(`
                            <div class="input-group date">
                                <input type="text" class="form-control form-control-sm datatable-input" readonly placeholder="From" id="filter_from"
                                 data-col-index="` + column.index() + `"/>
                                <div class="input-group-append">
                                    <span class="input-group-text"><i class="la la-calendar-o glyphicon-th"></i></span>
                                </div>
                            </div>
                            <div class="input-group date d-flex align-content-center">
                                <input type="text" class="form-control form-control-sm datatable-input" readonly placeholder="To" id="filter_to"
                                 data-col-index="` + column.index() + `"/>
                                <div class="input-group-append">
                                    <span class="input-group-text"><i class="la la-calendar-o glyphicon-th"></i></span>
                                </div>
                            </div>`);
                        break;

                    case 'Status':
                        var status = {
                            'true': {
                                'title': 'Active',
                                'class': 'label-light-primary'
                            },
                            'false': {
                                'title': 'Inactive',
                                'class': 'label-light-dark'
                            }
                        };
                        input = $(`<select class="form-control form-control-sm form-filter datatable-input" title="Select" data-col-index="` + column.index() + `">
                                    <option value="">Select</option></select>`);
                        column.data().unique().sort().each(function(d, j) {
                            $(input).append('<option value="' + d + '">' + status[d].title + '</option>');
                        });
                        break;

                    case 'Action':
                        var search = $(`
                            <button class="btn btn-black kt-btn btn-sm kt-btn--icon d-block">
                                <span>
                                    <i class="la la-search"></i>
                                    <span>Search</span>
                                </span>
                            </button>`);

                        var reset = $(`
                            <button class="btn btn-secondary kt-btn btn-sm kt-btn--icon">
                                <span>
                                   <i class="la la-close"></i>
                                   <span>Reset</span>
                                </span>
                            </button>`);

                        $('<th>').append(search).append(reset).appendTo(rowFilter);

                        $(search).on('click', function(e) {
                            e.preventDefault();
                            var params = {};
                            $(rowFilter).find('.datatable-input').each(function() {
                                var i = $(this).data('col-index');
                                if (params[i]) {
                                    params[i] += '|' + $(this).val();
                                } else {
                                    params[i] = $(this).val();
                                }
                            });
                            $.each(params, function(i, val) {
                                // apply search params to datatable.
                                if (table.column('6')){
                                    table.column('6').search( "^" + val, true, false, true );
                                }

                                table.column(i).search(val ? val : '', false, false);
                            });
                            table.table().draw();
                        });

                        $(reset).on('click', function(e) {
                            e.preventDefault();
                            $(rowFilter).find('.datatable-input').each(function(i) {
                                $(this).val('');
                                table.column($(this).data('col-index')).search('', false, false);
                            });
                            table.table().draw();
                        });
                        break;
                }

                if (column.title() !== 'Action') {
                    $(input).appendTo($('<th>').appendTo(rowFilter));
                }

            });

            // hide search column for responsive table
            var hideSearchColumnResponsive = function() {
                thisTable.api().columns().every(function() {
                    var column = this
                    if (column.responsiveHidden()) {
                        $(rowFilter).find('th').eq(column.index()).show();
                    } else {
                        $(rowFilter).find('th').eq(column.index()).hide();
                    }
                })
            };

            // init on datatable load
            hideSearchColumnResponsive();
            // recheck on window resize
            window.onresize = hideSearchColumnResponsive;

            $.fn.datepicker.defaults.format = "dd/mm/yyyy";
            $('#filter_from, #filter_to').datepicker();
        },
        columnDefs: [
            {
                targets: -1,
                title: 'Action',
                orderable: false,
                render: function(data, type, full, meta) {
                    return '<a href="/User/CustomerDetails?_uid=' + data + '" class="btn btn-clean btn-icon btn-xs" title="View details">
                                <span class="svg-icon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                        <g id="action_eye_btn" transform="translate(12811 -6182)">
                                        <rect id="Rectangle_8353" data-name="Rectangle 8353" width="24" height="24" transform="translate(-12811 6182)" fill="#fff" opacity="0"/>
                                        <g id="_01_align_center" data-name="01 align center" transform="translate(-12809 6184)">
                                            <path id="Path_37585" data-name="Path 37585" d="M19.851,9.318h0C19.12,7.718,16.25,2.5,10,2.5S.881,7.718.149,9.318a1.641,1.641,0,0,0,0,1.367C.881,12.283,3.75,17.5,10,17.5s9.119-5.218,9.851-6.818A1.64,1.64,0,0,0,19.851,9.318ZM10,15.834c-5.256,0-7.709-4.472-8.334-5.824C2.292,8.639,4.744,4.167,10,4.167S17.7,8.619,18.334,10C17.7,11.381,15.244,15.834,10,15.834Z" fill="#afafaf"/>
                                            <path id="Path_37586" data-name="Path 37586" d="M10,5.833A4.167,4.167,0,1,0,14.167,10,4.167,4.167,0,0,0,10,5.833ZM10,12.5A2.5,2.5,0,1,1,12.5,10,2.5,2.5,0,0,1,10,12.5Z" fill="#afafaf"/>
                                        </g>
                                        </g>
                                    </svg>
                                </span>
                            </a>
                            ';
                },
            },
            {
                targets: 4,
                render: function(data, type, full, meta) {
                    var status = {
                        1: {
                            'title': 'Email',
                            'state': 'warning'
                        },
                        2: {
                            'title': 'Facebook',
                            'state': 'primary'
                        },
                        3: {
                            'title': 'Google',
                            'state': 'success'
                        },
                        4: {
                            'title': 'Apple',
                            'state': 'dark'
                        },
                    };
                    if (typeof status[data] === 'undefined') {
                        return data;
                    }

                    return '<span class="label label-' + status[data].state + ' label-dot mr-2"></span>' +
                        '<span class="text-' + status[data].state + '">' + status[data].title + '</span>';
                },
            },
            {
                targets: 5,
                render: function(data, type, full, meta) {
                    return moment(data).format("DD/MM/YYYY");
                    //var date = new Date(data);
                    //return ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' +  ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + date.getFullYear();
                },
            },
            {
                targets: 6,
                render: function(data, type, full, meta) {
                    var status = {
                        'true': {
                            'title': 'Active',
                            'class': 'label-light-primary'
                        },
                        'false': {
                            'title': 'Inactive',
                            'class': 'label-light-dark'
                        },
                    };
                    if (typeof status[data] === 'undefined') {
                        return data;
                    }
                    return '<span class="label label-lg font-weight-bold ' + status[data].class + ' label-inline">' + status[data].title + '</span>';
                },
            }
        ]
    });

    //export csv
    var buttons = new $.fn.dataTable.Buttons(table, {
    buttons: [
            {
                extend: 'excelHtml5',
                text: 'Export in CSV',
                className: 'btn btn-black font-weight-bold font-size-sm px-6',
                exportOptions: {
                    columns: ':not(.action)'
                }
            }
        ]
    }).container().appendTo($('#export'));

};

return {

    //main function to initiate the module
    init: function() {
        initTable1();
    },

};

}();

jQuery(document).ready(function() {
    KTDatatablesSearchOptionsColumnSearch.init();

});

</script>

And here is the API response:

{"message":"Success","responseCode":2,"response":[{"userId":2,"email":"paula@example.com","name":"Paula","phoneNumber":"123456","roleId":0,"isActive":true,"isVerified":true,"registerType":1,"dateRegistered":"2021-12-13T15:19:19.385895"},{"userId":3,"email":"pau@example.com","name":"Pauleen","phoneNumber":"567y5756756767","roleId":0,"isActive":false,"isVerified":false,"registerType":2,"dateRegistered":"2021-12-12T15:34:16.171413"}],"validationMessages":[]}

I would really appreciate all of your answers. Thank you so much!!!



Source: https://stackoverflow.com/questions/70554490/datatable-custom-date-range-filter

(Speech/sound recognition) Why do most article/book show codes that train machine using JPEG file of plotted spectrogram?

Region quadtrees and efficient neighbour finding techniques in Go