1

I am using JSlink to change the cell color of a calculated column. I have to use Postrendering for that. The problem is that I cannot manipulate the cells.

I can color the rows but cannot color just one cell. As long as I am not using the view, don't know how to change the background color of just one cell. I have tried to use dRate.columnname, but it does not work. Here is my function for changing the whole row color:

function ColourDv(ctx) {

   for(var i=0; i < ctx.ListData.Row.length; i++)
   {
       var listItem = ctx.ListData.Row[i];
       var iid = GenerateIIDForListItem(ctx, listItem);
       var row = document.getElementById(iid);


        var dRate = listItem.Delivery_x0020_Rate;
        var nRate=dRate.replace('%','').replace(',','');

        if (nRate < 900)

        row.style.backgroundColor = "#d67763";

    else if( nRate < 950 )

    row.style.backgroundColor = "#f6ab3f";

    else 

        row.style.backgroundColor = "#8cba3f";
        }
           }
2

Please try below code as your OnPostRender function:

function ColourDv(ctx) {
    var header = document.querySelector("[name=Delivery_x0020_Rate]").parentNode;
    var index = [].slice.call(header.parentNode.children).indexOf(header) + 1;
    for (var i = 0; i < ctx.ListData.Row.length; i++) {
        var listItem = ctx.ListData.Row[i];
        var iid = GenerateIIDForListItem(ctx, listItem);
        var row = document.getElementById(iid);
        var dRate = listItem.Delivery_x0020_Rate;
        var nRate = dRate.replace('%', '').replace(',', '');
        var cell = row.querySelector("td:nth-child(" + index + ")")
        if (nRate < 900) {
            cell.style.backgroundColor = "#d67763";
        } else if (nRate < 950) {
            cell.style.backgroundColor = "#f6ab3f";
        } else {
            cell.style.backgroundColor = "#8cba3f";
        }
    }
}

Explanation

The changes are pretty simple.

First we get the index of your Delivery Rate column:

var header = document.querySelector("[name=Delivery_x0020_Rate]").parentNode;
var index = [].slice.call(header.parentNode.children).indexOf(header) + 1;

And then, instead of addressing the whole row, we only address the <TD> at this specific index:

var cell = row.querySelector("td:nth-child(" + index + ")")
if (nRate < 900) {
    cell.style.backgroundColor = "#d67763";
} 
...
  • Perfeeeect :) it works – Adi Sep 8 '16 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.