How to dynamically set columnDefs.targets value

How to dynamically set columnDefs.targets value

jircasjircas Posts: 2Questions: 2Answers: 0

I have a table with 4 columns (A, B, C, D). Sometime A and B are inputs, and C and D are output. Sometime reverse calculation is needed, which is C and D are inputs, and A and B are outputs. My problem is I need set different background-color for input and output columns.

The following code only set column 1 and 2 (inputs) background-color when data is added to table:

  var oupt = $j('#output').DataTable({ 
    dom: 'Brtip', 
    "columnDefs": [ {
        "targets": [0,1],
        "createdCell": function (td, cellData, rowData, row, col) {
            $j(td).css('background-color', 'pink')
        }
      } ]
  });

but it cannot dynamically set column 3 and 4 (inputs) background-color when making reverse calculation.

Any suggetions are appreciated.

Thank you

Answers

  • glendersonglenderson Posts: 231Questions: 11Answers: 29

    I would do it with rowCallback, and pass additional fields in the data that represent which class or color I want the individual cells to be. Using code like below, cells 0 & 1 will be applied a class based upon the named columns. Notice how you define your 4 columns but we pass 8 columns in the json data.

    ,"columns" : [
    {"data":"cell_0_value"}
    , {"data":"cell_1_value"}
    , {"data":"cell_2_value"}
    , {"data":"cell_3_value"}
    ]
    
    , "rowCallback": function(row, data, index) {
          var cellClass = data["cell_0_class"];
           $("td:eq(0)",row).addClass(cellClass);
    
          var cellClass = data["cell_1_class"];
           $("td:eq(1)",row).addClass(cellClass);
    }
    
    and the data would be
     { "data" : [
    {
    "cell_0_class":"inputClass"
    , "cell_0_value":15
    "cell_1_class":"inputClass"
    , "cell_1_value":30
    "cell_2_class":"outputClass"
    , "cell_2_value":10
    "cell_3_class":"outputClass"
    , "cell_3_value":25
    }
    , 
    "cell_0_class":"outputClass"
    , "cell_0_value":15
    "cell_1_class":"inputClass"
    , "cell_1_value":30
    "cell_2_class":"outputClass"
    , "cell_2_value":10
    "cell_3_class":"inputClass"
    , "cell_3_value":25
    }, 
    ...
    ]
    }
    
    
This discussion has been closed.