Conditional Formating of cells in Datatables

Conditional Formating of cells in Datatables

rohitrmsvermarohitrmsverma Posts: 2Questions: 0Answers: 0
edited October 2012 in General
hi buddies,

i have a table of nNumber of columns with numeric values(+/-) in each cell.
i need to color red the (-)ve and green the (+)ve.
please help.

Regards,
Rohit

Replies

  • girishmrgirishmr Posts: 137Questions: 0Answers: 0
    edited October 2012
    Two easy ways to do it :) or may be more - Gurus out there can answer

    1. Use classes and id/class selector to target the field
    2. Use aoColumnDefs

    1 Using classes
    ==========
    [code]
    .positive {
    background-color: green;
    }

    .negetive {
    background-color: green;
    }
    [/code]

    In you javascript

    [code]
    $('#amtfld').live('change', function(){
    if($('#amtfld').val() > 0) {
    $('#amtfld').addClass('positive');
    }
    else
    {
    $('#amtfld').addClass('negetive');
    }
    });
    [/code]

    2 Using aoColumnDefs:
    ===============
    [code]
    {
    "aTargets":[2], // Assuming this is where your amount field maps to
    "fnCreatedCell": function(nTd, sData, oData, iRow, iCol)
    {
    if(sData > 0)
    {
    $(nTd).css('background-color', 'green');
    }
    else
    {
    $(nTd).css('background-color', 'red');
    }
    }
    }
    [/code]

    Hope this helps.

    If there is a better way to do it please let me know. :)
  • rohitrmsvermarohitrmsverma Posts: 2Questions: 0Answers: 0
    thanks Girish,

    actually, i tried it another inefficient way .
    1. I labled those value at server side.
    2. $("#summaryTable tr td[id|='negvalcell']").each(function () {
    $(this).css({
    "color": "red"
    })
    });

    now the problem is, this formats only for first visible page. when i navigate to next page, no format is done.
This discussion has been closed.