≡

Datatables 3.1.5 - data populates, but data disappears when interact with table

Datatables 3.1.5 - data populates, but data disappears when interact with table

u20241229u20241229 Posts: 7Questions: 4Answers: 0

Problem

I am working on this test case:
https://live.datatables.net/butafeho/1/edit

Debugger

I can't get the debugger to work, sorry - it comes up with a message:

DataTables library not found!

Event though the start of the javascript is:

new DataTable('#colours');
window.DataTable = DataTable;

Disclaimer

I am a bit of a hobbyist so apologies for glaring mistakes.

Issue

When the page first loads, the datatable seems to initialise okay, sort of.

In the bottom-right it says:

Showing 0 to 0 of 0 entries

And clicking any column headings to sort data clears the table of any records.

I'm sorry for the basic question - I can't see what I have done wrong?

Thanks

Answers

  • allanallan Posts: 66,144Questions: 1Answers: 11,028 Site admin

    Hi,

    You are running into this FAQ:

    Q. I append a row to the table using appendChild(), but it is removed on redraw.

    You aren't using appendChild(), but it boils down to the same thing. Specifically, you are initialising the DataTable and then changing the DOM from under it.

    DataTables doesn't watch the DOM for .innerHTML changes made externally, so at the moment when you initialise the DataTable on #colours it has no data in it. Then you run populateTableRows and it uses .innerHTML to write the DOM rows in. But DataTables doesn't know that has happened!

    You could delay initialisation until the data has been written, but row.add() is perhaps a better option here.

              async function populateTableRows(colors){
                  for(let i=0;i<colors.length;i++){
                    table.row.add({
                      id: i+1,
                      name: colors[i].name,
                      hex: colors[i].hex
                    });
                  }
    
                  table.draw();
              }
    

    And your DataTable init becomes:

           let table = new DataTable('#colours', {
              columns: [
                {data: 'id'},
                {data: 'name'},
                {data: 'hex'},
                {
                  data: null,
                  defaultContent: '',
                  createdCell: (cell, cellData, rowData) => {
                    cell.style.backgroundColor = rowData.hex;
                  }
                },
              ]
            });
    

    i.e. use row.add() to add objects of the data, and let DataTables create the DOM for you.

    https://live.datatables.net/butafeho/3/edit

    Allan

Sign In or Register to comment.