How to change table columns dynamically

How to change table columns dynamically

mthaddonmthaddon Posts: 2Questions: 1Answers: 0

Link to test case: https://design-deploy.eu/datatables-test.html
Description of problem:
I'm trying to update a DataTable and load table columns dynamically based on the data, because I have a choice of data sources and depending on user input the amount of columns can change. I've created a reproducer for this in the link above. If you load the page and then click "Load one" you see 2 rows of data and 5 columns. If you reload the page and then click the "Load two" link you see 2 rows of data and 58 columns. The issue I'm having is trying to switch between the two without reloading the page. If you click "Load two" and then "Load one" without refreshing the page you get:

DataTables warning: table id=data-table - Incorrect column count. For more information about this error, please see https://datatables.net/tn/18

If you click "Load one" and then "Load two" without refreshing the page the columns seem to include the columns from "Load one" as well as the columns from "Load two" but the data remains the data from "Load one".

Any help appreciated.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 22,348Questions: 26Answers: 5,137
    Answer ✓

    You will need to use the destroy() API followed by emptying the table to change the number of columns. See the second example in the docs.

    Use DataTable.isDataTable() o determine if the table needs destroyed before initializing.

    Kevin

  • mthaddonmthaddon Posts: 2Questions: 1Answers: 0

    Awesome, thanks! Not sure how I missed that. What I've changed to get it working is from this:

          if (typeof table !== "undefined"){
            table.destroy();
          }
    
          var columnData = [];
          for (const header in data[0]){
            $("#data-table-thead").append('<th scope="col">' + header + '</th>');
            columnData.push({data: header});
          }
    
    

    To this:

          if (typeof table !== "undefined"){
            table.destroy();
            $("#data-table").empty();
          }
    
          var columnData = [];
          for (const header in data[0]){
            columnData.push({data: header, title: header});
          }
    
    

    So basically adding the .empty(); and defining the title property in columnData rather than trying to manipulate it separately.

Sign In or Register to comment.