Ajax: how to address DataTable cells' content properly by JavaScript?

Ajax: how to address DataTable cells' content properly by JavaScript?

andrew45andrew45 Posts: 24Questions: 8Answers: 0

DataTable is the most powerful tool to sort data in tables but I still struggle how to handle DataTable cells' content properly by JavaScript. I use Ajax to load data into the table and then I can't find the part of my data in the DOM.

I've created a simple table model of what I want to have done.

https://jsfiddle.net/andrew45/g5v03pt7/2/

I load the test_array.txt file into my table, then I add an additional row (jRow = $('<tr class=user_row>').append). Later I need to modify the "Days" column by JavaScript (document.getElementsByClassName('days')[i].innerHTML = days).

1) The main problem is that I can access through DOM to the first page of my DataTable only (paging: true). Note that the "Days" are not calculated in the second or other pages. Unfortunately, I need a large table, so I can't always use the option paging: false which helps.

2) Is there a smarter option to check the DataTable availability without using setTimeout() function? You can uncomment two alerts in my code to understand better what's going on.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949
    Answer ✓

    The main problem is that I can access through DOM to the first page of my DataTable only (paging: true)

    That is correct. The only part of the table in the DOM is the page being displayed. The rest of the data is stored in Datatables data cache. The best way to get and update the data is to use Datatables APIs. You can use the data() method to get the raw data and in many cases set the data. You can use the node() method to get the td or tr. See the docs for the following APIs:

    row().data()
    row().node()
    cell().data()
    cell().node()
    column().data()
    column().nodes()

    There are plural forms of the APIs to get multiple instances, for example: rows(), cells() and columns().

    Is there a smarter option to check the DataTable availability without using setTimeout() function?

    If you want to run certain code after the Datatable has initialized you can use the initComplete callback or the init event - both are essentially the same.

    Kevin

This discussion has been closed.