NotToBrag NotToBrag - 2 months ago 6
Javascript Question

Merge DataTable functions together

I have the following code which functions as intended:

var $datatable = $('#datatable-keytable');
var item = [["myName","myNumber"],
["myName2","myNumber2"]];

$datatable.DataTable({
keys: true
});

for(int i in item) {
$datatable.DataTable().row.add([
item[i][0],
item[i][1]
]).draw();
}


However I get the error:
Cannot reinitialize DataTable
see: https://datatables.net/manual/tech-notes/3

How can I merge both these functions together to prevent this error from showing up?

Answer

You need to use dataTable.api()

DataTables has an extensive API which can be used to access the data contained in a table and otherwise manipulate the table after the table initialization has completed.

Since you are using DataTable you already have an API instance , so try this

$datatable.api().row.add([
   item[i][0],
   item[i][1]
]).draw();

EDIT: you need to initialize it like this

var $dataTable = $('#datatable-keytable').dataTable({
  keys: true
});

You can also use retrive

DataTables as a retrieve option which can be used to tell DataTables that you are aware that the initialisation options can't be changed after initialisation, and that should that occur, that you just want the DataTable instance to be returned.

$datatable.DataTable( {
  retrieve: true
} ).row.add([
              item[i][0],item[i][1]
           ]).draw();