how to destroy and reinitialize the datatable

how to destroy and reinitialize the datatable

SriRishithaSriRishitha Posts: 42Questions: 4Answers: 0

i created a datatable dynamically like this

var table = $('#equictntbl').DataTable({

                    retrieve: true,
                    columns: cols,
                    ServerSide: true,
                    dom: 'Bfrtip',
                    buttons: [
                       {
                           extend: 'print',
                           title: 'Report   ',
                           //text: '<i class="fa fa-print"></i> Print',
                           //title: $('h1').text(),
                           exportOptions: {
                               //columns: ':not(.no-print)'
                               columns: ':visible', stripNewlines: true
                           },

                           orientation: 'landscape',
                           pageSize: 'C2',
                           footer: false
                       },
                        {
                            extend: 'excelHtml5', title: 'Report', footer: true, exportOptions: {
                                columns: ':visible', stripNewlines: false
                            },
                            orientation: 'landscape',
                            pageSize: 'LEGAL',
                        },
                        {
                            extend: 'pdfHtml5', title: 'Report',
                            columns: ':visible',
                            orientation: 'landscape',
                            pageSize: 'C2',
                            text: '<i class="fa fa-file-pdf-o"> PDF</i>',

                            footer: false
                        },
                        {
                            extend: 'colvis',
                            columnText: function (dt, idx, title) {
                                return (idx + 1) + ': ' + title;
                            },
                            postfixButtons: ['colvisRestore']
                        },
                         {
                             extend: 'pageLength', footer: false, exportOptions: {
                                 stripNewlines: false
                             }
                         },
                    ],
                    iDisplayLength: 25,
                    lengthMenu: [[10, 25, 50, -1],
                        ['10', '25', '50', ' all']
                    ],
                    pagingType: "full_numbers",
                    deferRender: true,

                });
                table.rows.add(resp).draw();
                debugger

            }
            else if (resp.length == 0) {
                debugger
                toastr.error("No data found");
                $('#reportdiv').hide();
        }
            else {
                debugger
                $('#reportdiv').hide();
                toastr.error("Please fill all the details");
            }
        }
    });

if ($.fn.DataTable.isDataTable('#viewtbl')) {

                    $('#equictntbl').dataTable().fnClearTable();
                    $('#equictntbl').dataTable().fnDestroy();

                }

Replies

  • rduncecbrduncecb Posts: 125Questions: 2Answers: 28
    edited September 2017

    Use .DataTable() (with a capital D) and then you can use functions like clear and destroy

    See the first FAQ - https://datatables.net/faqs/index#Most-common-FAQs

  • SriRishithaSriRishitha Posts: 42Questions: 4Answers: 0

    $('#equictntbl').DataTable().clear();
    $('#equictntbl').DataTable().destroy();
    i write like this but my table not reloading with new columns data.

  • SriRishithaSriRishitha Posts: 42Questions: 4Answers: 0

    discussion closed

  • pepsi7959pepsi7959 Posts: 1Questions: 0Answers: 0

    //Destroy the old Datatable
    $('#equictntbl').DataTable().clear().destroy();

    //Create new Datatable
    $('#m_device_table').DataTable({...})

    Ref

  • badbytebadbyte Posts: 33Questions: 7Answers: 0

    I'm using DataTables 1.10 and did a clear before destroying the Datatables but when I'd want to reinitialize the table again I but I get in the console output of the browser the following:
    ```TypeError: h is undefined

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    Hi @badbyte,

    It's working as expected here. Can you modify that test case to demonstrate the problem, please.

    Cheers,

    Colin

  • dt_userdt_user Posts: 51Questions: 16Answers: 0

    Good night. I wanted to know if the code above will print child rows without clicking on the drop down button to show the child rows.

  • tangerinetangerine Posts: 3,342Questions: 35Answers: 394

    @dt_user - your question seems to have no relevance to this thread. I suggest you start a thread of your own.

  • sooli86sooli86 Posts: 2Questions: 0Answers: 0

    I found that the sequence is very important.

    var tableId = "#myTable";
    // clear first
    if(tableObj!=null){
    tableObj.clear();
    tableObj.destroy();
    }

    //2nd empty html
    $(tableId + " tbody").empty();
    $(tableId + " thead").empty();

    //3rd reCreate Datatable object
    tableObj= $(tableId).DataTable({
    ...
    });

  • Ian SkeaffIan Skeaff Posts: 1Questions: 0Answers: 0

    @sooli86 - thank you - the "2nd empty html" code is indeed important prior to re-initializing the table.

    Cheers.

  • dmeisterdmeister Posts: 10Questions: 2Answers: 0

    I'm doing something very similar to what you're doing in the snippet you provided. I have responsive: true and when I resize the browser window to be narrow like a mobile device, the responsiveness kicks in as expected. However, If I go through the lifecycle of where I clear and destroy the table and then initialize -- while in "mobile" view, the responsiveness is lost. Has anyone experienced this?

           function initializeDataTablesSettings(customColumns) {
                if ($.fn.dataTable.isDataTable('#EZAPOPTable')) {
                    $('#EZAPOPTable').DataTable().clear();
                    $('#EZAPOPTable').DataTable().destroy();
                    $('#EZAPOPTable').empty();
                    getData.offSet = undefined;  // necssary to set the static value to undefined so that the offset is valid during initial runs
                    // re Add CSS to table
                    $('#EZAPOPTable').addClass("usa-table views-table views-view-table cols-8 sticky-enabled sticky-table");
                    $('#EZAPOPTable').css("width","100%")
    
                }
                dtEZAPOPS = $('#EZAPOPTable').DataTable({
                    columns: customColumns,
                    paging: false,
                    lengthChange: false,
                    autoWidth: true,
                    responsive: true,
                    columnDefs: [
                        //  {orderData:[15], targets: [1]},
                        //  {visible: false, targets: [6,7,8]},
                        //  {width: "45%", targets: 3 },
                        //  {width: "20%", targets: [0,2] }
                    ],
                    buttons: [
                        {
                            extend: 'copy',
                            messageTop: getExportHeader,
                            messageBottom: getExportFooter,                         
                        },
                        'csv',
                        { 
                            extend: 'excel', 
                            messageTop: getExportHeader,
                            messageBottom: getExportFooter,
                            exportOptions: {
                                stripNewLines: false    
                            }
                        },
                        {   
                            extend: 'pdf',
                            messageTop: getExportHeader,
                            messageBottom: getExportFooter,
                        }, 
                        {
                            extend: 'print',
                            messageTop: getExportHeader,
                            messageBottom: getExportFooter,
                        }
                    ],
                    oLanguage: {
                        sSearch: "Keyword Search:"
                    },
                    dom: '<"top"p>Blrtip',
                    bInfo: false,
                    //lengthMenu: [[5,10,15,25,50,100],[5,10,15,25,50,100]]
                });
                $('#EZAPOPTable').addClass("usa-table views-table views-view-table cols-8 sticky-enabled sticky-table");
                $('#EZAPOPTable').css("width","100%");
    
  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736

    $('#EZAPOPTable').css("width","100%");

    Take a look at this example. It states that style="width:100%" should be applied to the table tag directly so Datatatbles can use it to size the table. Try this instead of adding with .css().

    Kevin

  • dmeisterdmeister Posts: 10Questions: 2Answers: 0

    Thanks Kevin,
    I do have the width applied to the table:

    <table id="EZAPOPTable" class="usa-table views-table views-view-table cols-8 sticky-enabled sticky-table" style="width:100%;"></table>

    Just to reiterate, If I load the table in desktop mode and then resize the browser window to Mobile width using the mouse, The columns are responsive as the last one is hidden and the green plus sign appears. However, when I refresh the screen while at the Mobile width, all of the columns appear in the dt thus violating responsiveness.
    If I define the columns statically in the HTML, the dt works as expected, but I need to dynamically change the number and value of columns.

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736

    However, when I refresh the screen while at the Mobile width, all of the columns appear in the dt thus violating responsiveness.

    How are you refreshing the screen? Is this a refresh of the whole page or are you just refreshing the table data and re-initializing Datatables? Please provide more details of what you are doing.

    Can you post a link to your page or a test case showing the issue so we can help debug?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • dmeisterdmeister Posts: 10Questions: 2Answers: 0

    Hi Kevin,
    Please load the following sample I created:
    http://ubuntu2005.eastus.cloudapp.azure.com/programlistingPOC.html

    To recreate the behavior, perform the following:
    1. Load the url in the browser in desktop mode
    2. Click on the "get data" button
    3. After the data loads, resize the browser window horizontally until it's at it's narrowest
    4. You should see the green plus circles which indicates that the page is responsive
    5. Click the "get data" button again
    6. The green plus circles will be gone and the page isn't responsive anymore
    7. If you slightly resize the browser, then the page is responsive again

    Any insight on how to resolve this will be appreciated.

    Thanks

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736

    @dmeister Thanks for the test case. I used $('#programs').DataTable().responsive.recalc(); in the console after the second get data button and it adjusted the display. Try using responsive.recalc() after tblPrograms.order([15, 'asc'],[0, 'asc']).draw(); in your Ajax success function.

    Kevin

  • dmeisterdmeister Posts: 10Questions: 2Answers: 0

    Hi Kevin,
    Your suggestion did the trick! Thanks again for your help.

    Daoud

Sign In or Register to comment.