Destroy doesn't destroy

Destroy doesn't destroy

ghenneghenne Posts: 3Questions: 1Answers: 0

I'm trying to overwrite a table with a new one. Here's the code:

<table id="DataTable1" class="table table-striped table-bordered" width="100%">
    <thead><tr><th>Name</th><th>Age</th><th>Salary</th></tr></thead>
    <tbody><tr><td>TigerNixon</td><td>61</td><td>$320,800</td></tr>
    <tr><td>GarrettWinters</td><td>63</td><td>$170,750</td></tr></tbody>
</table>
<button onclick="updateTable()">Update Table</button>

<script>
function updateTable() {
    table = $('#DataTable1').DataTable( {
        data: dataSet, //define elsewhere
        destroy: true,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ]
    } );
}
</script>

You can try it here:
https://www.nsbasic.com/i/Datatable/DT_Test.html

I get "Uncaught TypeError: Cannot read property 'style' of undefined" at jquery.dataTables.js:5570.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,275Questions: 26Answers: 4,765

    Your table has 3 columns but you define 6 in DataTables. Add 3 more columns and it should work.

    Kevin

  • ghenneghenne Posts: 3Questions: 1Answers: 0

    Are you sure? From the docs on the Destroy function:

    This function can be useful if you require to destroy and create new tables based on new criteria with different initialisation settings or a different number of columns in the table, as they cannot be change on-the-fly through the API.

  • kthorngrenkthorngren Posts: 20,275Questions: 26Answers: 4,765
    edited February 2017 Answer ✓

    I see. You are using the destroy which allows for changing the Datatables options but doesn't create a new table. If you want to create a new table then you will need to use both destroy and empty. Similar to the second example:
    https://datatables.net/reference/api/destroy()#Examples

    Kevin

  • ghenneghenne Posts: 3Questions: 1Answers: 0

    That was it - thank you. Here is the working code:

    function updateTable() {
        table = $('#DataTable1').DataTable();
        table.destroy();
        $('#DataTable1').empty();
        
        table = $('#DataTable1').DataTable( {
            data: dataSet,
            destroy: true,
            empty: true,
            columns: [
                { title: "Name" },
                { title: "Position" },
                { title: "Office" },
                { title: "Extn." },
                { title: "Start date" },
                { title: "Salary" }
            ]
        } );
    }
    
This discussion has been closed.