change cell value color

change cell value color

miltontmiltont Posts: 20Questions: 7Answers: 0

I have been trying to use createdCell to change the color of a cell in column 8 if it is < 1 to red.

The example shows:

"targets":3,
"createdCell": function (td, cellData, rowData, row, col){
if (cellData < 1 ) {
$(td).css('color', 'red')
}
}

I cannot work out where I should put this inside my script.
columnDefs: [ ** I tried putting it here** //This makes the column align to the following

My script is as follows:

<script>
                $(document).ready( function () {
                $('#myTable').DataTable(
                    {   
                        "order":[[7,"desc"],[6,"desc"],[5,"desc"],[8,"desc"]],   //Specifies Column to use for sorting 0 = 1st Column and direction = descending - make sure you add a comma at the end
                        "dom": '<lif<t>p>',                                      //Adds the Total Players to the middle
                        lengthMenu: [[100,10,25,50,-1],[100,10,25,50,"All"]],    //First row of Numbers is what is shown initiallly, Second row of Numbers is what is in the Drop Down Menu selector
                        fixedHeader: {headerOffset: 80},                         //Makes the Header fixed        
                        columnDefs: [                                            //This makes the column align to the following
                            { targets: [1,2,3,4,5,9,10], className: 'dt-body-center'},
                            { targets: [6,7,8,11], className: 'dt-body-right'},
                            { targets: [5,6,7], render: DataTable.render.number( ',', '.', 0 )}   //Add a thousand seperator
                                 
                        ]   
                    });    
                } );
            </script>

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,202Questions: 1Answers: 2,592
    Answer ✓

    You'd add it into columnDefs, so you'd change this:

                                { targets: [6,7,8,11], className: 'dt-body-right'},
    

    to be something like:

     { targets: [6,7,11], className: 'dt-body-right'},
     {targets: 8, 
        "createdCell": function (td, cellData, rowData, row, col){
           if (cellData < 1 ) {
              $(td).css('color', 'red')
           }
         }
     },
    

    Colin

  • miltontmiltont Posts: 20Questions: 7Answers: 0

    Thanks Colin,
    worked like a charm!

Sign In or Register to comment.