fmDestroy() breaks my table's HTML

fmDestroy() breaks my table's HTML

AndravenAndraven Posts: 2Questions: 1Answers: 0

Hello There

SOME CONTEXT:
I was using DataTables 1.9.4 and everything was fine. I had to upgrade to 1.11.3 for security reasons and now it seems that fnDestroy() works differently and breaks my table.

The error: Cannot read property ‘mData’ of undefined

How do I initialize DataTables:
1. A column with its header and data, is being added to the tables's HTML
2. After the HTML is updated with the new column the DataTable is being initialized on that HTML
3. If a DataTable is already initialized on that HTML its being fnDestroy()-ed first.

So if I have 5 columns for example I will initialize a DataTable 5 times and each time I will fnDestroy() the previous instace first.

Sounds mad? Yes!
But we have functionality depending on this logic so I don't want to change it now. And although not very clean it was working fine so far.

THE PROBLEM
It seems after 1.20(including) fnDestroy() works differently, meaning it destroys parts of my header which causes the number of td elements in the table body to differ from number of th elements in the table header. Which causes this error (Cannot read property ‘mData’ of undefined)

I'm sharing a CodePen here that showcases a working table with older version and a non-working table with newer version. Depending on which script tag you enable on the top.

Link: https://codepen.io/ChakraPen/pen/gOywQPV

Thanks in advance

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin
    edited March 15 Answer ✓

    If you check the console in your example you will see an error message like:

    Uncaught TypeError: datatable.fnDestroy is not a function

    That is because 1.10+ use the return from $().DataTable() as a DataTables API instance. The legacy fnDestroy() method is only returned if you use $().dataTable(). Indeed, it isn't even returned with the current 2.0 releases since the legacy API has been completely removed.

    However, it is more than that. You are manipulating the table's DOM structure by adding the columns, then destroying the table. It needs to be the other way around. DataTables restores the table into the state it knows - so your added columns get removed. Destroy the table then add the new column and finally initialise again: https://codepen.io/DataTables/pen/yLraZKY .

    That uses 2.0.2, since 1.11 is no longer supported.

    Allan

  • AndravenAndraven Posts: 2Questions: 1Answers: 0

    Thank you so much! I've been stuck at this for couple of days and your advice was exactly what I needed!

Sign In or Register to comment.