Hide empty column after search

Hide empty column after search

JoeWhiteStarJoeWhiteStar Posts: 2Questions: 1Answers: 0

Hi,

My question is similar to the discussion from https://datatables.net/forums/discussion/68443/filtering-hide-an-empty-column. However, I am using the standard search box and I would like to hide the columns with empty data after the search. So the hiding criteria is based on the filtered results.

My question is that how do I obtain the row indexes for the visible rows (after search)? So that I can use that information to determine the targeted cells in a column to check their content.

Joe

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,537Questions: 26Answers: 4,816
    edited August 2023 Answer ✓

    One option might be to use the search event so it runs for each search. In the event handler use rows().every() with a selector-modifier of { search: "applied" } to loop all the rows displayed by the search filter. In the loop build an array of column indexes to hide. Then use columns().visible() to hide the columns. Maybe something like this in the search event handler:

    var columnIndexes = [];
    table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
        var data = this.data();
        // ... do something with data(), or this.node(), etc
    } );
    table.columns().visible( true );  // Reset to show all columns
    
    // If empty data found hide columns
    if ( columnIndexes.length ) {
        table.columns( [columnIndexes] ).visible( false );
    }
    

    I didn't test this code but it should give you the idea.

    To make this more efficient you may want to compare the columnIndexes to the previous indexes to see if there are changes. Also this will run with each keystroke. Maybe you will want it to run only when enter is used in the search input. There are threads for this.

    Kevin

  • JoeWhiteStarJoeWhiteStar Posts: 2Questions: 1Answers: 0

    Hi Kevin,

    Really apricated your help. That worked perfectly.

    Joe.

  • kthorngrenkthorngren Posts: 20,537Questions: 26Answers: 4,816

    Glad it helped!

    Kevin

Sign In or Register to comment.