How to hide specific range of columns by jQuery function rather than in data tables definition

How to hide specific range of columns by jQuery function rather than in data tables definition

rdmrdm Posts: 194Questions: 55Answers: 4

I've been requested to dynamically show/hide columns based on a function call rather than the method shown in the column visibility examples, where columns are toggled with a button.

Here's a very simplified snippet of code. How would I be able to hide/show columns in an if-statement? The code works well so far.

I can't find any examples show/hide columns in this scenario. How would I achieve this?


const contentTable = $("#ContentTable").DataTable({ dom: "lBfiprt", buttons: ["excelHtml5", "print"], "scrollX": true }); function filterContentTable(columnIndex, question, marked) { // in initial state, all columns are shown if (marked === true) { const qCol = question + 7; contentTable.columns().search(""); if (columnIndex === 3) { contentTable.column().search(""); } // hide columns 8 to 16 except for qCol (let's pretend qCol === 12) if (columnIndex === 4) { contentTable.column(2).search("ACT 1"); contentTable.column(qCol).search("P"); } if (columnIndex === 5) { contentTable.column(2).search("ACT 1"); contentTable.column(qCol).search("F"); } if (columnIndex === 6) { contentTable.column(2).search("ACT 2"); contentTable.column(qCol).search("P"); } if (columnIndex === 7) { contentTable.column(2).search("ACT 2"); contentTable.column(qCol).search("F"); } } else { contentTable.columns().search(""); } contentTable.draw(); }

This question has an accepted answers - jump to answer

Answers

  • LapointeLapointe Posts: 430Questions: 81Answers: 4
    Answer ✓

    Hi
    did you try

    column.visible( ! column.visible() )
    

    or have a look here

  • rdmrdm Posts: 194Questions: 55Answers: 4

    I figured it out eventually.

    function toggleColumns(qCol) {
        for (let i = 7; i <=21; i++) {
            
            if (i === qCol) {
                contentTable.column(i).visible(true);
            } else {
                contentTable.column(i).visible(false);    
            }
            
        }
        contentTable.draw();
    
    }
    
  • LapointeLapointe Posts: 430Questions: 81Answers: 4
    edited November 2020

    hi...
    In fact you fucntion set all columns not visible else qCol
    perhaps logical toggle

    function toggleColumns(qCol) {
        contentTable.column(qCol).visible( ! contentTable.column(qCol).visible());
        contentTable.draw();
    }
    
This discussion has been closed.