Skip to content Skip to sidebar Skip to footer

Set SType To All AoColumns On Dynamic Jquery Datatable

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, a

Solution 1:

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);

Solution 2:

The other answers are more complex than they need to be.

Javascript version:

var i, aoColumns = [];
for (i = 0; i < totalCol; i++) {
  aoColumns.push( { 'sType': 'string' } );
}

ECMAScript 6 version:

aoColumns.fill( { 'sType': 'string' }, 0, totalCol )

This may work on your browser if a polyfill exists for the JavaScript array.fill command in any libraries you use.

PHP (server side) version:

<?php
//  array( 'stype' => "string" ); for old PHP
$columns = 6;
$aoColumns = array_fill( 0, $columns, [ 'stype' => 'string' ] );
print json_encode($aoColumns);
?>

Solution 3:

I solved this by using parseJSON and converting string to a JSON:

aoColumns = '[{"sType":"string"}';
i = 0;
tc = totalCol;
while(i<tc){
    aoColumns += ',';
    aoColumns += '{"sType":"string"}';
    i++;
}
aoColumns += ']';

// if totalCol == 3 then
// aoColumns will return [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}]
aoColumns = $.parseJSON(aoColumns);

this worked!


Post a Comment for "Set SType To All AoColumns On Dynamic Jquery Datatable"