Dynamic header - how?

Dynamic header - how?

2233arunkumar2233arunkumar Posts: 1Questions: 1Answers: 0

I have a if case, if the case is true -> then the table will have 4 columns. If the case failed -> i will have 3 columns. How to do this with datatable?
if (condition) {
table with 4 headers
} else {
table with 3 headers
}
Kindly suggest your opinion.

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,598
    edited May 2018

    Hi @2233arunkumar ,

    You specify which table to use with DataTables by the jQuery selector, that table can have any number of columns if it's just in the HTML. If you're receiving the column data from objects returned from an Ajax query, then you'll need to just have the test before the initialisation.

    if(columns === 4) {
      columns = [
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "extn" }
        ];
    } else {
      columns = [
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "extn" },
        { "data": "start_date" }
        ];
    }
    
    $('#example').DataTable({
      "ajax": "data/objects.txt",
      "columns": columns
    
    });
    

    Cheers,

    Colin

This discussion has been closed.