An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up saying "Unable to get property 'style' of undefined or null reference."


var htmlTable = "<table class='display responsive no-wrap cell-border compact' style='margin: 0 !important' width='100%' id='policyTable'>" +
            "<thead>" +
            "<tr class='cell-border custom-header-footer tableHeaders' id='tableHeaders'>" +
            "<th>Policy Details</th>" +
            "</tr>" +
            "</thead>" +
            "</table>";

function InitAndLoadTableData(tableData, tableId, exportTitle) {            

    if ($.fn.DataTable.fnIsDataTable("#" + tableId)) {
        var oldTable = $("#" + tableId).DataTable();
        oldTable.destroy(true);
        $("#divFor_" + tableId).append(htmlTable);
    }

    var table = $('#' + tableId)
        .DataTable({
            data: tableData,
            dom: "<'row' <'col-md-12'B>><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
            "searching": false,
            "paging": false,
            "info": false,
            "ordering": false,
            //destroy: true,
            responsive: true,
            processing: false,
            columns: tableColumns,
            buttons: [
                { extend: 'copy', className: 'btn red btn-outline', title: exportTitle },
                { extend: 'pdf', className: 'btn green btn-outline', title: exportTitle },
                { extend: 'excel', className: 'btn yellow btn-outline', title: exportTitle },
                { extend: 'csv', className: 'btn purple btn-outline', title: exportTitle }
            ]
        });

    table.buttons().container().appendTo($('.col-md-12:eq(0)', table.table().container()));         

}

Answer №1

Instead, you should consider using the following code snippet:

$('#example').DataTable( { destroy: true, // Add any additional customization here } );

Answer №2

Encountered a similar issue where the intention matched dynamic columns.

To resolve it, I had to implement the code below:

let dataTable = $("#table-id").DataTable();
dataTable.clear();
dataTable.destroy();

// After determining the columns, recreate by initializing DataTable
// An important step - I remove and recreate <th> based on received columns
// Otherwise, there may be a 'style' error due to data and table column mismatch.

The dataTable.clear() call was crucial as it removed existing HTML content. Adding destroy: true in the DataTable constructor didn't work, but dataTable.destroy() did the job effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guidelines for sending JSON Data via Request Body using jQuery

I'm not well-versed in jQuery, so consider me a beginner. Here's my code that is not correctly handling JSON data submission via Request Body. <!doctype html> <html lang="en> <head> <title>jQuery JSON Data Submission ...

What strategies are effective for handling state reactively in Vuex?

Currently, I am facing an issue with my vuex store. I have implemented two different actions in my store, one being reactive and the other not. However, I specifically need the loadSlidesEach() action to be reactive so that the data gets updated accordingl ...

Obtain the vector for the right hand using three.js

I am looking to obtain the forward vector of an Object3D in Three.JS var forward = new THREE.Vector3(); object.getWorldDirection(forward); Is there a way to retrieve the right-hand side vector of the object within Three.JS framework? ...

Instantiating a Google Cloud Function with a Real-Time Database Trigger Path

Looking for advice on Google Cloud functions triggered by RTDB - specifically, how to access the trigger path of an existing function. I'm encountering an issue when copying functions for different environments (dev vs. production) as the trigger path ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...

The res.download method in a node.js express app does not display the correct filename upon downloading

Starting with what I have: core.app.get('/download/:key', function (req, res) { require("./../../module/fileupload.js").download(req.params.key, function(file, filename) { console.log(file + " - " + filename); if (file != nul ...

Highcharts failing to connect the dots with lines between data points

UPDATE: After some investigation, it turns out that the issue stemmed from inconsistent intervals. By following the solution outlined in this post, the problem was easily resolved. I have implemented highcharts to create a chart, where the initial data po ...

What is the best way to rearrange DOM elements using the output of a shuffle function?

Looking for a solution to shuffle and move around cards in an HTML memory game? Let's analyze the current setup: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

What is the procedure for controlling a Textfield in the Browser with a Java code?

I have an automation problem that I am trying to solve. The task involves accessing a specific webpage with two editable text fields and some other elements, extracting the content from these text fields using a Java program to filter keywords and generate ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

Implement a redux-form within a react-bootstrap modal

I am facing a challenge with incorporating a multipage 'redux-form' form into a react-bootstrap modal. My goal is to have the form displayed within the modal overlay when the modal is opened. How can this be achieved? The code below is producin ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

Collapsing or expanding the Material UI accordion may lead to flickering on the page

import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Accordion from "@material-ui/core/Accordion"; import AccordionDetails from "@material-ui/core/AccordionDetails"; import Accordi ...

The requested path /releases/add cannot be located

In my CRUD application, I have a feature that allows users to create releases by adding a version and description. This is achieved through a button and input fields for the details. <button (click)="addRelease(version.value, description.value)" [d ...

Is there a way for me to execute a function multiple times in a continuous manner?

I am attempting to create a blinking box by calling a function within itself. The function I have is as follows: $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeToggle("slow"); }); }); <script src="https://a ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

Updating Button Color Based on Input Field Value in EJS

How can I change the color of a button in EJS when the input value changes? <div> <textarea name="mytextarea" id="inputcontent" cols="30" rows="3" style="margin-top: 10px; margin-bottom: 10px; f ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

stop the menu component from triggering a re-render

I am facing an issue where the menu opens and closes briefly when I refresh the page. I want to find a way to prevent this re-rendering process. Every time I refresh, my console.log shows: false 'open' navigation.jsx:23 item navigation.jsx: ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...