How to initialize a table that is rendered inside a Javascript function called by a button event?

How to initialize a table that is rendered inside a Javascript function called by a button event?

KroolKrool Posts: 1Questions: 1Answers: 0

Usually, I do the initialization of a table in the global scope to avoid re-initialiazations. But in this specific scenario, I'm rendering an entire form inside a funtion caused by a button click event. In this form, there's a datatable but the problem is that for the initialization to happens, it needs an existing html element to render it. Since the initialization is globally, it occurs at the begginng of the .js load and the table does not exisists at this point just after a button is clicked:

// Global scope
const columnDefs_numbersTable =[ // columns ]
 
const numbersTable = $('#numbersTable').DataTable({
            'columns': columnDefs_numbersTable ,
            paging: false,
            'info': false,
            responsive: true,
            fixedHeader: true,
            'scrollY': '300px',
            'scrollX': '300px',
            'scrollCollapse': true,
        });
 
function loadTable() {
    $('#formToCreate').html(
        `
            <table class="display" id="numbersTable" style="width:100%">
            </table>
        `
    );

Note: I tried a close solution with an global constant variable that contains an arrow function that returns the datatable:

const numbersTable = () => {
  const columnDefs_numbersTable =[ // columns ]
 
  return $('#numbersTable').DataTable({
            'columns': columnDefs_numbersTable,
            paging: false,
            'info': false,
            responsive: true,
            fixedHeader: true,
            'scrollY': '300px',
            'scrollX': '300px',
            'scrollCollapse': true,
        });
}

And then call numbersTable() at the moment I need it to show but this causes a re initialization to happen (at .js load and when the function is called), so I receive the following warning: Cannot reinitialise DataTable.
(docs: https://datatables.net/manual/tech-notes/3)
Something courious about this is second scenario is that even if I recieve the warning alert, the table renders, but useless. In the first scenario, table doesn't render at all.
Tanks for the support.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    The easiest way would be to call $.fn.dataTable.isDataTable() to see if the table has already been initialised. That should do the trick,

    Colin

This discussion has been closed.