Change a cell's CSS based on a different cell's value

Change a cell's CSS based on a different cell's value

Taylor514ceTaylor514ce Posts: 74Questions: 8Answers: 0
edited July 2017 in Free community support
columnDefs: [ {
      targets: 2,
      createdCell: function (td, cellData, rowData, row, col) {
        if ( cellData == 'Inactive' ) {
          $(td).css('color', 'red');
          $(td).css('text-decoration', 'line-through');
        }
      }
    } ],

In the above extract from a Datatable object definition, I add an inline style to a TD element based on that cell's value.

How can I change a cell's style based on another cell's value? If cell "5" contains "checked out" as a value, I'd like to change the css of cell "0", which is the name of the "thing" (think of a document, book, whatever) that has been "checked out".

I suspect I need to reference the "row" object passed into the createdCell function and work my way back to the previously created cell in that row.

If I try: $(row).$('td:nth-child(1)').css('color', 'green'); the table stays on "Loading".

TDG

This question has accepted answers - jump to:

Answers

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30
    edited July 2017 Answer ✓

    Third argument (rowData) for function defined by columns.createdCell option contains full row data.

    For example, if you want to change color of the cell in first column (index 0) based on data in the sixth column (index 5), you can use the following options:

    columnDefs: [ {
        targets: 0,
        createdCell: function (td, cellData, rowData, row, col) {
            if ( rowData[5] === 'Inactive' ) {
                $(td).css('color', 'red');
            }
        }
    } ]
    

    See more articles about jQuery DataTables on gyrocode.com.

  • Rob BrunRob Brun Posts: 56Questions: 2Answers: 14
    edited July 2017 Answer ✓

    Hi Taylor514ce, you can do it in the createdRow Callback

     "createdRow": function (row, data, index) {
    },
    
    

    The data parameter contains the data for your row

    access the cell like

    if(data["CheckedOut"] ===  "checked out"){
       $('td', row).eq(0).css('color', 'red');
    }
    

    https://datatables.net/reference/option/createdRow

This discussion has been closed.