Puneet_2696717
Puneet_2696717

Reputation: 221

How can I store data to javascript global variable in jquery Datatable

I have a jquery datatable which has large number of data. I am performing an action that selected(checkbox checked) rows will only be binded inside it. Now I have to reset the jquery datatable i.e all the records should be displayed again. So what should be the approach? whether I need to store data into global variable and then clear it and assign this data again to Datatable or some another approach.

////////// on document.ready/////////
$('#mytable').DataTable();
 GlobalTable = $('#mytable').DataTable();
 GlobalTab = GlobalTable.data();


/////////the below code is for Binding the data again/////////
var table = $('#mytable').DataTable();
table.clear().draw();
for (i = 0; i < GlobalTab.toArray().length; i++) {
     table.row.add(GlobalTab.toArray()[i]).draw();
   }                  
 table.draw();

These above lines I have tried which is not working properly as expected.

Upvotes: 1

Views: 3690

Answers (1)

&#193;ngela
&#193;ngela

Reputation: 1425

I'm not sure what was not working about your code (couldn't reproduce with your snippets), but I can suggest a couple of things:

  • Store only the data in the variables: GlobalTab = GlobalTable.data().toArray()
  • You do not need to redraw after clearing the table, or after adding each row, you only need to redraw when you are finished changing the data
  • You don't need to iterate over the rows, you can add them all in a single call

So to bind the data again you would do something like:

var table = $('#mytable').DataTable();
table.clear();
table.rows.add(GlobalTable);
table.draw();

You can see a working example in this jsfiddle

Upvotes: -1

Related Questions