How to preserve data filter after sort/search

How to preserve data filter after sort/search

rdmrdm Posts: 192Questions: 54Answers: 4
edited September 2018 in DataTables 1.10

I have looked on prior answers to this question and see "this documentation is for prior versions of data tables..."

In my scenario, I this function that filters a table.

This command initializes the table on document load.

$(".display").DataTable({
                dom: "lBfiprt",
                buttons: ["excelHtml5", "print"],
                columnDefs: [{ visible: false, targets: [6, 7] }],
                stateSave: true // this has no effect
            });

When the user selects buttons on the page, the following function is called, which correctly filters the table. However, when the user sorts the table, the filter goes away. I used stateSave:true, to no effect. What is the correct way to preserve a table filter when sorting, using Data Tables version 1.10?

function filterTable() {
                var detail = $(".display").DataTable();
                if (filterMonth !== "All") {
                    $.fn.dataTable.ext.search.push(
                        function(settings, data, dataIndex) {
                            if (filterBy === "IEP") {
                                return data[6] === filterMonth;
                            } else {
                                return data[7] === filterMonth;
                            }
                        });
                    detail.draw();
                    $.fn.dataTable.ext.search.pop();
                } else {
                    detail.search('').columns().search('').draw();
                }
            }

Answers

  • rdmrdm Posts: 192Questions: 54Answers: 4
    edited September 2018

    I figured it out -- and it appears to work for me. The problem was that I when I searched for a filtering method, I found a method that worked, but didn't play will with saveState. After digging around some more, I found a nicer method that does play well with saveState.

    function filterTable() {
        var detail = $(".display").DataTable();
    
        if (filterMonth !== "All") {
            if (filterBy === "IEP") {
                detail.column(6).data().search(filterMonth);
            } else {
                detail.column(7).data().search(filterMonth);
            }
        } else {
            detail.columns().data().search("");
    }
    
This discussion has been closed.