How to filter the closest datatable?

How to filter the closest datatable?

aolkoaolko Posts: 5Questions: 1Answers: 0

jQuery: 3.5.1
Datatables: 1.13.2
Browser: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.57,gzip(gfe)
OS: Windows 10 22H2 (19045.2604)
Debug: (404) https://debug.datatables.net/ucuyes

I use fomantic (semantic) UI and i have my tables in accordion. Each table is located in a container with two calendar fields for filtering. How do i only filter this (closest) table on interaction with calendar fields?

Here's my JS:

$.with(`.kab-cal-container`, function() {
            var Container = $(this);
            var table = $(this).find('.kab_tbl_transfers');
            var calStart = $('#kab-dateFilter-start',this);
            var calEnd = $('#kab-dateFilter-end',this);
            var calClear = $('#kab-dateFilter-clear',this);

            setTimeout(function() {
                mydataTable = table.DataTable({
                    ordering: true,
                    info: false,
                    searching: true,
                    "lengthChange": false,
                    //paging: false,
                    scroller: true,
                    scrollY: 300,
                    //scrollX: false,
                    //stateSave: true,
                    order: [[1, 'desc']],
                    language: {
                        url: '{{tpl.glob_asset_path}}/js/datatables/plugins/i18n/ru.json',
                    },
                    dom: "<'ui fluid stackable grid'"+
                        "<'row'"+
                        //"<'eight wide column'f>"+
                        "<'right aligned eight wide column'l>"+
                        ">"+
                        "<'row dt-table'"+
                        "<'sixteen wide column'tr>"+
                        ">"+
                        "<'row'"+
                        "<'twelve wide column'p>"+
                        ">"+
                        ">"
                });
            },1000);

            $.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
                var min = calStart.calendar('get date')[1];
                var max = calEnd.calendar('get date')[1];

                var dateString = DOMPurify.sanitize(data[2]);
                var date = moment(dateString.replace(/<br\s*[\/]?>/gi, " "), "DD.MM.YYYY HH:mm:ss").toDate();

                //console.log(`vals: ${min} ${max}`);
                //console.log(date);

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

            calStart.calendar({
                type: 'month',
                firstDayOfWeek: 1,
                today: true,
                formatter: {
                    date: function (date, settings) {
                        if (!date) return '';
                        var day = date.getDate() + '';
                        if (day.length < 2) {
                            day = '0' + day;
                        }
                        var month = (date.getMonth() + 1) + '';
                        if (month.length < 2) {
                            month = '0' + month;
                        }
                        var year = date.getFullYear();
                        return day + '.' + month + '.' + year;
                    },
                    time: 'H:mm',
                    cellTime: 'H:mm'
                },
                text: {
                    days: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
                    dayNamesShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
                    dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
                    months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
                    monthsShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
                    today: 'Сегодня',
                    now: 'Сейчас',
                    am: 'ДП',
                    pm: 'ПП',
                    weekNo: 'Неделя'
                },
                endCalendar: calEnd
            });
            calEnd.calendar({
                type: 'month',
                firstDayOfWeek: 1,
                today: true,
                formatter: {
                    date: function (date, settings) {
                        if (!date) return '';
                        var day = date.getDate() + '';
                        if (day.length < 2) {
                            day = '0' + day;
                        }
                        var month = (date.getMonth() + 1) + '';
                        if (month.length < 2) {
                            month = '0' + month;
                        }
                        var year = date.getFullYear();
                        return day + '.' + month + '.' + year;
                    },
                    time: 'H:mm',
                    cellTime: 'H:mm'
                },
                text: {
                    days: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
                    dayNamesShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
                    dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
                    months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
                    monthsShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
                    today: 'Сегодня',
                    now: 'Сейчас',
                    am: 'ДП',
                    pm: 'ПП',
                    weekNo: 'Неделя'
                },
                startCalendar: calStart
            });

            $('#kab-dateFilter-start, #kab-dateFilter-end',this).on('change', function() {
                var $table = $(this).closest('table');
                console.log($table);

                var dateStart = calStart.calendar("get date")[1];
                var dateEnd = calEnd.calendar("get date")[1];
                var dateStartFormatted = moment(dateStart).format('DD.MM.YYYY');
                var dateEndFormatted = moment(dateEnd).format('DD.MM.YYYY');

                var myDatatable = $table.DataTable();

                console.log(`${dateStartFormatted} - ${dateEndFormatted}`);

                if (dateStartFormatted && dateEndFormatted) {
                    //console.log(`Start: ${startDate} End: ${endDate}`);
                    //filterTableByDateRange(dateStartFormatted, dateEndFormatted);
                    myDatatable.columns(2).search(dateStartFormatted + ' - ' + dateEndFormatted).draw();
                    //mydataTable.draw();
                }
            });
            function filterTableByDateRange(startDate,endDate) {
                //var start__formatted = formatDate(startDate);
                //var end__formatted = formatDate(endDate);

                mydataTable.columns(2).search("").draw();
                //mydataTable.columns(5).search(start__formatted + '-' + end__formatted).draw();
                mydataTable.columns(2).search(startDate + ' - ' + endDate).draw();
                //console.log(start__formatted + '-' + end__formatted);
                //mydataTable.draw();
            }

            calClear.on("click",function () {
                calStart.calendar('clear');
                calEnd.calendar('clear');
                mydataTable.columns(2).search("").draw();
            })

        });

Answers

  • rf1234rf1234 Posts: 2,809Questions: 85Answers: 406
    edited March 2023

    I don't know about filtering the "closest" data table but I know how to filter just the table(s) I want to filter. Here is something from my own coding. I only want to filter "tblLoginLogoutLog".

    $.fn.dataTable.ext.search.push(function (settings, data, dataIndex, row, counter) {
        if (settings.nTable.id !== 'tblLoginLogoutLog'){
            return true;
        }
        var time = row.login_logout_log.when.slice(-8).substr(0,5);
        var threshold = $('#loginLogoutLogStartTime').val();
        if ( threshold <= "" ) {
            threshold = "24:00";
        }
        if ( time >= threshold ) {
            return true;
        }
        return false;
    });
    

  • colincolin Posts: 15,177Questions: 1Answers: 2,590

    We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • aolkoaolko Posts: 5Questions: 1Answers: 0

    Test case: https://codepen.io/aolko/pen/PodmjZm

    Note: This test case contains severely cut down recreation of my workflow, js may be broken as well, which doesn't represent the current state of my workflow.

  • rf1234rf1234 Posts: 2,809Questions: 85Answers: 406

    Your test case produces an error.

    All you would need to do is to determine the id of the closest data table.

    Then you could do this:

    if (settings.nTable.id !== <the closest id you determined> ){
        return true;
    }
    
  • aolkoaolko Posts: 5Questions: 1Answers: 0

    Sorry guys, still clueless

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794
    edited March 2023

    Try using table().node() to get the ID, something like this:

    $( mydataTable.table().node() ).attr('id')
    

    Not sure why you are using the setTimeout function but you will want to move the search plugin inside this function to use the above. For example:

                setTimeout(function() {
                    mydataTable = table.DataTable({
                        ordering: true,
                        info: false,
                        searching: true,
                        "lengthChange": false,
                        //paging: false,
                        scroller: true,
                        scrollY: 300,
                        //scrollX: false,
                        //stateSave: true,
                        order: [[1, 'desc']],
                        language: {
                            url: '{{tpl.glob_asset_path}}/js/datatables/plugins/i18n/ru.json',
                        },
                        dom: "<'ui fluid stackable grid'"+
                            "<'row'"+
                            //"<'eight wide column'f>"+
                            "<'right aligned eight wide column'l>"+
                            ">"+
                            "<'row dt-table'"+
                            "<'sixteen wide column'tr>"+
                            ">"+
                            "<'row'"+
                            "<'twelve wide column'p>"+
                            ">"+
                            ">"
                    });
    
                $.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
                   if (settings.nTable.id !== $( mydataTable.table().node() ).attr('id') ){
                       return true;
                   }
    
                    var min = calStart.calendar('get date')[1];
                    var max = calEnd.calendar('get date')[1];
     
                    var dateString = DOMPurify.sanitize(data[2]);
                    var date = moment(dateString.replace(/<br\s*[\/]?>/gi, " "), "DD.MM.YYYY HH:mm:ss").toDate();
     
                    //console.log(`vals: ${min} ${max}`);
                    //console.log(date);
     
                    if (
                        ( min === null && max === null ) ||
                        ( min === null && date <= max ) ||
                        ( min <= date && max === null ) ||
                        ( min <= date && date <= max )
                    ) {
                        return true;
                    }
                    return false;
                });
                },1000);
    

    Kevin

  • aolkoaolko Posts: 5Questions: 1Answers: 0
    edited March 2023

    Not sure why you are using the setTimeout function

    i'm using it so headers/scrolling don't break

  • aolkoaolko Posts: 5Questions: 1Answers: 0

    Maybe there's a way to pass the filters through native datatable fields?

  • rf1234rf1234 Posts: 2,809Questions: 85Answers: 406
    edited March 2023

    You got a suggested solution from Kevin and me.

    If that doesn't work for you please post a test case highlighting the issue as per the forum rules. Thank your for your understanding.

    Why would you want to pass the filters through datatable fields? Where would you pass them to? The server? Please note: Search is performed client side unless you have "serverSide" activated.

Sign In or Register to comment.