Javascript – Set sType to all aoColumns on dynamic jquery datatable

datatablejavascriptjquery

I'm working on a huge custom datatable function and I've a simple issue, I need to set 'sType' to all 'aoColumns', but these tables are dynamic, so they may have 6 or 10 columns, and I can't find a way to do, I have already tried the following options:

//doesn't work
"aoColumns": [{"sType":"string", "aTargets": ["_all"]}],

//this works, but its not dynamic :/
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}],

and I can't do this using server-side

obs.: I have a var with number of columns

6 columns
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}],
10 columns
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}],

Thanks anyway

Best Answer

Server-side PHP: Well, If you are creating the table in php, then you should be able to build a string with all the needed array parts that you can plug into the javacript.

<?php
$colnum = 6;
$i = 1;

$aocolumns = array();

while($i <= $colnum){
  $aocolumns[] = '{"sType":"string"}';
  $i++;
}

$aocolumns = join(",",$aocolumns);
$aocolumns = '[' . $aocolumns . ']';

?>

then drop it in like

"aoColumns": <?=$aocolumns?>

Javascript: Assuming you get the columns back from the ajax as an array called "cols", you can try this for loop. :

var aocolumns = [];
for(i in cols){
  var ao = {"sType":"string"}; 
  aocolumns.push(ao);
}
alert(aocolumns);