if inside column definition?

if inside column definition?

redsunsetredsunset Posts: 44Questions: 15Answers: 0

Hi!
I would like to add a dynamic column to my table based on a variable that has different values.

I am using:

var sroles = ... different int value ... ; 

  // On page load: datatable
  var table_cards = $('#table_cards').DataTable({
    "ajax": "data-search.php,
    "columns": [
      { "data": "data1" }, 
      { "data": "data2" },
      { "data": "data3" },
      { "data": "data4",   "sClass": "cardname" },
      { "data": "data5" },
      { "data": "data6"},
      { "data": "data7", "sClass": "integer2"},
      { "data": "data8", "sClass": "integer"},
      { "data": "data9", "sClass": "integer"},
      { "data": "data10"},
      { "data": "data11"},
    if(sroles == 1) { THAN ADD  { "data": "data12" } }

    ],

is that possible? thank you in advance!

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    Answer ✓

    Doing something like that is not proper Javascript syntax. You can create a Javascript variable containing the base columns array. Then use the Javascript push() method to push the additional column if required. For example:

    var columns = [
          { "data": "data1" },
          { "data": "data2" },
          { "data": "data3" },
          { "data": "data4",   "sClass": "cardname" },
          { "data": "data5" },
          { "data": "data6"},
          { "data": "data7", "sClass": "integer2"},
          { "data": "data8", "sClass": "integer"},
          { "data": "data9", "sClass": "integer"},
          { "data": "data10"},
          { "data": "data11"}
    ];
    
    if(sroles == 1) {
        columns.push( { "data": "data12" } );
    }
    
      var table_cards = $('#table_cards').DataTable({
        "ajax": "data-search.php,
        "columns": columns
    });
    

    Kevin

  • redsunsetredsunset Posts: 44Questions: 15Answers: 0

    great! thank you very much!

This discussion has been closed.