Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  161] [ 5]  / answers: 1 / hits: 11799  / 10 Years ago, sat, october 11, 2014, 12:00:00

I want to make a function to create a new DataTable. If a table already exists, I would like my function destroy the existing table and create the new one.



I did this:



$.ajax().done(function(response){
Init_DT(response['cols'], response['data']);
});

function Init_DT(cols, data){

if($('#mytable tr').length > 0){
table.destroy();
}

var table = $('#mytable').DataTable({
data: data,
columns: cols
});

}


This function works well to initiate my first table but I get Cannot read property 'destroy' of undefined on subsequent calls.


More From » jquery

 Answers
0

Local JavaScript Variables.



a variable defined inside a function has a Local Scope. It is destroyed when function finishes.



function myFunction() {
var myVar = value;}


this function myVar will be destroyed after the function has done its work. in the next call it will be defined again.



Use global variable. i.e define it outside the function and then use it.
i.e



var myVar='value';function myFunction(){//here myVar can be accessed}


or inside your function assign a value to a variable it will become global.



function myFunction(){ myVar = 'value'; }


now myVar will also be global.



Therefore you need to use



table = $('#mytable').DataTable({
data: data,
columns: cols
});


reference: w3Schools JS Variable Scope


[#41961] Thursday, October 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
renag

Total Points: 22
Total Questions: 97
Total Answers: 95

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;