change row colour

change row colour

dasapadasapa Posts: 17Questions: 3Answers: 0
edited March 2013 in General
Someone knows? ...can I change background colour row with the value depending of var id? I use server processing with jsonp

var sData = oTable.fnGetData( this );
var id = sData[4];

I obtain the value of id but i dont know how change colour?

if id="1"- BG colour Red
else if id="2" - BG colour Green

Thanks

Replies

  • GregPGregP Posts: 500Questions: 10Answers: 0
    edited March 2013
    To do it outside of the initialization, I'd need to know what "this" is in your context. Assuming "this" is a row, though, it should be simple:

    [code]if (id == "1") { this.css({"background-color":"red"}) }
    else if (id == "2") { this.css({"background-color":"blue"}) }
    [/code]

    ** note for the above: not sure if your "this" is already a jQuery object. If it's a DOM node rather than a jQ object, you'll need to change it to $(this)

    I do my row colouring in the fnRowCallback rather than retrieving the data object and then processing:

    [code]
    "fnRowCallback": function( nRow, aData ) {
    var id = aData.myID; // ID is returned by the server as part of the data
    var $nRow = $(nRow); // cache the row wrapped up in jQuery
    if (id == "1") {
    $nRow.css({"background-color":"red"})
    }
    else if (id == "2") {
    $nRow.css({"background-color":"blue"})
    }
    return nRow
    }
    [/code]

    *** Additional note: I'm using .css() for the sake of simplicity, but a better practice would be to use .addClass() instead, and then define your styles for that class in your CSS file
  • dasapadasapa Posts: 17Questions: 3Answers: 0
    Thanks, is easy using fnRowCallback.
  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin
    If the data doesn't change you might want to consider using fnCreatedRow as it will be a bit more efficient.

    Allan
  • GregPGregP Posts: 500Questions: 10Answers: 0
    Neat. I didn't know about fnCreatedRow; I think there are places in my application I can use it!
  • dasapadasapa Posts: 17Questions: 3Answers: 0
    Date change...run ok using "fnRowCallback"

    Now i have other problem...javascript (no datatables I think)..

    With aDate[4] obtain a value format date (2013-03-09), I want to change row colour with number of days ( today - aDate[4])

    [code]
    if (Today - aDate[4]> X) { //X is number of days
    $nRow.css({"background-color":"blue"}) }
    else {
    $nRow.css({"background-color":"green"}) } [/code]

    I have used code below but no run...I think problem is aData[4].getTime()
    [code]
    var today=new Date();
    var df = today.getTime()-aData[4].getTime();
    var days = Math.floor(df/(1000 * 60 * 60 * 24));
    if(days>5){
    $nRow.css({"background-color":"blue"})}
    else{
    $nRow.css({"background-color":"green"})}
    }[/code]
This discussion has been closed.