Update column color dynamically

Update column color dynamically

mc2devmc2dev Posts: 33Questions: 6Answers: 0

Hi,
I'm looking for a way to set a column color.
Here, I'm using JQuery to do the trick but if I add a new row, it takes the previous color...

$(tableId)
    .find('th, td')
    .each(function (i, th) {
      if (th.className.includes(col)) { // some conditions
        $(th).css('background-color', newColor) // I want to set the DataTable object instead
      }
})

Thanks for your support!

Answers

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736

    Use the createdRow or columns.createdCell to set the color.

    Kevin

  • mc2devmc2dev Posts: 33Questions: 6Answers: 0

    Thank you for your help Kevin but this code doesn't work as expected:

    createdCell: function (td) {
            $(td).css('background-color', "red")
    }
    

    Any ideas of my mistake?

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736

    It works here:
    http://live.datatables.net/bofagita/1/edit

    Please update the test case to show the issue.

    Kevin

  • mc2devmc2dev Posts: 33Questions: 6Answers: 0
    edited January 2022

    Hi Kevin,

    I can't find a way to solve my problem and my table structure is too big and specific to update your example.
    Otherwise, is there a way to set column background color of the DataTable object?

    Thank you for your time.

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736
    edited January 2022

    I can't find a way to solve my problem and my table structure is too big and specific to update your example.

    The test case doesn't need to contain your full solution. In fact its better if it doesn't. It just needs to contain a subset of the solution that demonstrates the issues.

    You posted 3 lines of code. Do you have them inside either columnDefs or columns? If not it won't work.

    Other options are to set a classname to the column using columns.classname. Then use CSS to apply the settings you want to that classname.

    Oh, and there is rowCallback which is similar to createdRow.

    Kevin

Sign In or Register to comment.