hide empty columns (ajax data)

hide empty columns (ajax data)

johan.steurs@staff.telenet.bejohan.steurs@staff.telenet.be Posts: 4Questions: 1Answers: 0

with a datatables instance populated by ajax, how can i detect columns without data?
i want to hide those columns ...

the hiding part is not the problem;
table.column(columnIndex).visible(false); // table is a DT instance

how do i determine which column (i.e. columnIndex) does not have data, and especially after the ajax loaded the data?

what i currently have is this:

table.columns().flatten().each( function ( colIdx ) {
    var columnData = table{{loop.index}}.columns(colIdx).data()
    if (columnData.length < 1) {
        table.column(colIdx).visible(false);
    }
});

which does not work, i suspect because the data is not loaded at this point ...
currently i use an object to define the ajax, should i change this to a function and use the callback directly?

i searched this forum and google as well, but couldn't get all this stuff clear in my head, so any help that gets me back on track is appreciated, thanks.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    I think your solution is fairly close, but data() will return an array item for each row in the table, which might include empty strings - so the count will always be >0 if you have any rows.

    What you could do is use join() to create a string based on the data and then check its length. If 0 then there is no data in the table!

    table.columns().flatten().each( function ( colIdx ) {
        var columnData = table{{loop.index}}.columns(colIdx).data().join('');
        if (columnData.length < 1) {
            table.column(colIdx).visible(false);
        }
    });
    

    The other option would be to use cells() with a function for a selector for the row selector which would give a list of rows which don't have any data - but I suspect the above might be just as efficient if not more so.

    Regards,
    Allan

  • johan.steurs@staff.telenet.bejohan.steurs@staff.telenet.be Posts: 4Questions: 1Answers: 0

    thanks Allan

    for completeness: putting the code in "initComplete": function(settings, json){ .... } helped too ;)

  • johan.steurs@staff.telenet.bejohan.steurs@staff.telenet.be Posts: 4Questions: 1Answers: 0

    For others: please note that "table{{loop.index}}" needs to be just "table". Where table is a DataTables instance.

    I was careless cleaning the code for this example, the loop index is Python Jinja template code, because i have several DataTables instances in one html

This discussion has been closed.