Extraction of Data from an Object to change -ve numbers to RED

Extraction of Data from an Object to change -ve numbers to RED

cpshartcpshart Posts: 246Questions: 49Answers: 5

I am trying to add some code to change any negative numbers to the colour RED.

I have the following code snippet as part of my code which is able to change the cells in the column of my table to RED, if I remove the if condition.

The transaction type ( "Buy" or "Sell" ) is given by my SQL table.column of dm_transactions.tranasaction_type

How can I store the value of dm_transactions.tranasaction_type into the variable str, so only -ve of column 7 given by aTargets will be RED in colour.

    $('#transactions').DataTable( { 
    "aoColumnDefs": [ {
      "aTargets": [7],
      "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
          str = JSON.stringify(sData);
          console.log("The value of sData is " +str);
        if ( str === "Sell" )         
        {
          $(nTd).css('color', 'red')
        }
      }
    } ],

The JSON data in the console is shown below

The value of sData is ["row_2",{"user_id":"2","transaction_type":"Buy","transaction_date":"2017-08-08","portfolio_id":"1","stock_id":"16","quantity":"5281","price":"470.74","charges":"131","total":"24990.8"},{"code":"SFT_DEA_CO","name":"Selftrade Dealing Colin"},{"symbol":"BP..L","name":"BP"}]
(index):506 

I know I may be able to use a string extraction function, I am not sure if that is the approved method.

Many Thanks

Colin

This question has an accepted answers - jump to answer

Answers

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

    Hi @cpshart ,

    I'm not quite following - I think you'r saying you want to colour one cell based on another cell. If so, the third argument to columns.createdCell is the complete row data, so you can that as in this example here.

    Hope that helps,

    Cheers,

    Colin

  • cpshartcpshart Posts: 246Questions: 49Answers: 5

    Hi Colin

    Thank you, that is exactly what I require, all working now.

                                /* CHANGE CELL COLOUR TO RED FOR NEGATIVE NUMBERS */             
                                 createdCell: function (td, cellData, rowData, row, col){
                                     if (rowData.dm_transactions.transaction_type === 'Sell' && rowData.dm_transactions.total > 0) {
                                         $(td).css('color', 'red')
                                     }
                                 }}
    
    

    I have a couple of other hopefully quick queries which I will raise now.

    Many Thanks

    Colin

This discussion has been closed.