user4780686
user4780686

Reputation:

Get DataTable object from HTML element

I have a problem where I am trying to access a data table object of a particular HTML element.

I have looked at the docs for JQuery Data Table and am using this example: https://datatables.net/reference/option/retrieve

This however, does not work. Here is my code in my global file main.js:

function initTable () {
    return $(".dynamic-table").DataTable({
        "aaSorting": [],
        "scrollY": 530,
        "scrollCollapse": true,
        "lengthMenu": [
            [100, 400, 1000, 5000, -1],
            [100, 400, 1000, 5000, "All"]
        ],
        "retrieve": true
    });
}

$(document).ready(function() {
    initTable();
});

Now inside of my other file I attempt to retrieve the object:

$(document).ready(function() {
    var table = initTable();
});

This does not retrieve the object but instead it initializes the object again and causes the table to render twice.

enter image description here

I have also tried:

$(document).ready(function() {
    var table = $(".dynamic-wide-table").DataTable();
});

because I have read some threads saying that a blank initialization will just retrieve the object.

Neither of these solutions work. If anybody knows what I am doing wrong I would greatly appreciate it! Thanks.

Upvotes: 7

Views: 20540

Answers (3)

Hicham O'Sfh
Hicham O'Sfh

Reputation: 841

For getting the instance when you have a selector ("#table_id" or ".display-tables" for example):

var instance = new $.fn.dataTable.Api( 'selector' );

DataTable.net docs

Upvotes: 1

Chris Hopkins
Chris Hopkins

Reputation: 334

$(".dynamic-wide-table").DataTable();

Referencing like the above is the correct way to obtain a Data Tables API reference.

You can test this in the datatables examples https://datatables.net/examples/ajax/objects.html and then enter the below JS into your console. You will see it does not redraw the table or create a second table.

  var table = $('#example').DataTable()

Also see the API docs https://datatables.net/reference/api/ that clearly state this method.

Using the table object you can do any datatable operation.

Upvotes: 16

Imran
Imran

Reputation: 2089

You may use extend ..

   $.extend( true, $.fn.dataTable.defaults, {
            "bFilter": true,

        } );

Upvotes: 1

Related Questions