Re initialize datatables

Re initialize datatables

daws14daws14 Posts: 3Questions: 1Answers: 0
edited May 12 in Free community support

I apoligize beforehand, as english is not my first language.

i have a project in school, where we want to display 4-5 tables on a screen, where we will use a dropdown menu as such:
<label for="tableSelector">Choose a table:</label>
<select id="tableSelector">
<option value="car_table">Biler</option>
<option value="lease_table">Leasingaftaler</option>
<option value="condition_report_table">Tilstandsrapporter</option>
<option value="damage_table">Skader</option>
</select>

Now when i view the page i can see alle the tables individually when i choose them, however i can´t revisit the table once i have seen it once. I assume it has something to do with destroy and rebuild/initilize or something along those lines.

Ive only just started dipping my toes in js, so i am i deep water. Please help.
here is a snippit of a general table and the js

<

div class="dataTable" id="customer_table">

<

table class="display compact">
<thead>
<tr>
<th>ID</th>
<th>Fornavn</th>
<th>Efternavn</th>
<th>Email</th>
<th>Cpr-nummer</th>
<th>TelefonNummer</th>
<th>Adresse</th>
<th>By</th>
<th>Postnummer</th>
<th>Bil id</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="customer: ${customers}">
<td th:text="${customer.customerId}" />
<td th:text="${customer.firstName}" />
<td th:text="${customer.lastName}" />
<td th:text="${customer.email}" />
<td th:text="${customer.cprNumber}" />
<td th:text="${customer.phoneNumber}" />
<td th:text="${customer.address}" />
<td th:text="${customer.city}" />
<td th:text="${customer.postalCode}" />
<td th:text="${customer.fkVehicleId}" />
<td>
<form th:action="@{/deleteCustomer}" method="post">
<input type="hidden" name="customerId" th:value="${customer.customerId}">
<button type="submit">Delete</button>
</form>
</td>

JS:
$(document).ready(function () {
const $tableSelector = $('#tableSelector');

    const initializedTables = {};


    $('.dataTable').hide();


    const defaultTableId = $tableSelector.val();
    $('#' + defaultTableId).show();
    initializeTable(defaultTableId);


    $tableSelector.on('change', function () {
        const selected = $(this).val();


        $('.dataTable').hide();

        // Show the selected table
        $('#' + selected).show();

        // Destroy and reinitialize the table
        initializeTable(selected);
    });

    function initializeTable(tableId) {
        const $tableElement = $('#' + tableId).find('table.display');


        if (initializedTables[tableId]) {
            initializedTables[tableId].destroy(); // Destroy the existing DataTable
        }


        initializedTables[tableId] = $tableElement.DataTable({
            paging: false,
            scrollCollapse: true,
            scrollY: '50vh',
            destroy: true
        });
    }
});

I recognizes that there is a table when i revisit it, since it says showing 1-11 entrie, but not data shows.

When i refresh the site, i can see them again.

Thank you in advance

Answers

  • allanallan Posts: 64,390Questions: 1Answers: 10,629 Site admin

    I think you could just remove the call to initializeTable(selected); in the tab change function. Previously with tabs you would have to call columns.adjust() when a table is made visible, but with the latest versions it will handle that automatically.

    Unless you are changing the content of the tab, there is no need to destroy and reinitialise the table.

    Ive only just started dipping my toes in js, so i am i deep water.

    lol - it only gets deeper the more you know ;). Your code is looking good there though!

    Allan

  • daws14daws14 Posts: 3Questions: 1Answers: 0

    @allan
    Thank you for the quick reply. it sort of fixed it aha. However alle the other tables are no longer longer using your library it seems. its just an ordinary table, but i can switch between them with no problem. But the first Datatable is styilized, which is this one
    const defaultTableId = $tableSelector.val();
    $('#' + defaultTableId).show();
    initializeTable(defaultTableId);

    The others have no styiling, and when i swich back to the default one (which is styled) i cant see any data, only the "showing x out of x entries"

  • kthorngrenkthorngren Posts: 21,974Questions: 26Answers: 5,073
    edited May 12

    Possibly change the initializeTable() function to run once on page load (after the HTML tales are added to the document) to initialize all the tables at once. Something like this:

        function initializeTable(tableId) {
            const $tableElement = $('table.display');
      
            initializedTables = $tableElement.DataTable({
                paging: false,
                scrollCollapse: true,
                scrollY: '50vh',
            });
        }
    

    You can use the tables() API to access a particular Datatable's API stored in initializedTables. Or if you want initializedTables to be an object with the table id as the key then loop through $tableElement using jQuery each() to individually initialize the Datatables.

    Is there a reason you are destroying the Datatable? Are you changing the config or the data in the table? If not then you don't need to destroy and reinitialize the Datatable.

    Kevin

  • daws14daws14 Posts: 3Questions: 1Answers: 0

    @kthorngren Thank you for the reply. I tried running the function once per page load, but it only initialized the first table and none of the others. On another note. When i try to run the script without the destroy functions, so like this:

    $(document).ready(function () {
    // Cache the table selector
    const $tableSelector = $('#tableSelector');

        // Keep track of initialized tables
        const initializedTables = {};
    
        // Initially hide all tables
        $('.dataTable').hide();
    
        // Show and initialize the default table
        const defaultTableId = $tableSelector.val();
        $('#' + defaultTableId).show();
        initializeTable(defaultTableId);
    
        // On table selection change
        $tableSelector.on('change', function () {
            const selected = $(this).val();
    
            // Hide all tables
            $('.dataTable').hide();
    
            // Show the selected table
            $('#' + selected).show();
    
            initializeTable(selected);
        });
    
        function initializeTable(tableId) {
            const $tableElement = $('#' + tableId).find('table.display');
    
            // Reinitialize the DataTable for the selected table
            initializedTables[tableId] = $tableElement.DataTable({
                paging: false,
                scrollCollapse: true,
                scrollY: '50vh',
    
            });
        }
    });
    

    the site says "DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. For more information about this error, please see https://datatables.net/tn/3"

  • kthorngrenkthorngren Posts: 21,974Questions: 26Answers: 5,073

    I tried running the function once per page load, but it only initialized the first table and none of the others.

    Not sure what you tried nor if all the HTMl tables are built on page load. We would need to see a test case with this to understand your full solution.

    Without knowing how your solution works, sometimes code snippets aren't enough to fully understand, then maybe the best option is to use DataTable.isDataTable() to determine if the Datatable is initialized or not. Maybe something like this:

        function initializeTable(tableId) {
            const $tableElement = $('#' + tableId).find('table.display');
     
            // Initialize the Datatable if nots not already initialized
            if (!$.fn.DataTable.isDataTable( $tableElement )) {
              initializedTables[tableId] = $tableElement.DataTable({
                  paging: false,
                  scrollCollapse: true,
                  scrollY: '50vh',
     
              });
            }
        }
    

    Kevin

Sign In or Register to comment.