jqGrid: change background color of row based on row cell value by column name

The main ideas to change the background color of the row you will find here and here. I recommend you to read this answer which discussed different advantages and disadvantages of different approaches.

To get column index from the column name you can use following simple function:

var getColumnIndexByName = function(grid, columnName) {
        var cm = grid.jqGrid('getGridParam','colModel'),i=0,l=cm.length;
        for (; i<l; i++) {
            if (cm[i].name===columnName) {
                return i; // return the index
            }
        }
        return -1;
    };

The function getColumnIndexByName($("#list"), 'MyColumnName') will get you the index in colModel of the ‘MyColumnName’ column.

To change the background color you can follow the example

loadComplete: function() {
    $("tr.jqgrow:odd").addClass('myAltRowClass');
}

from the answer, but instead of ':odd' filter you can write the filter yourself using jQuery.filter. Inside of the filter you can use :nth-child() to access the data from the corresponding <td> element (see here)

UPDATED: You can do the following (very close to the code from the another answer):

loadComplete: function() {
    var iCol = getColumnIndexByName($(this),'closed'),
        cRows = this.rows.length, iRow, row, className;

    for (iRow=0; iRow<cRows; iRow++) {
        row = this.rows[iRow];
        className = row.className;
        if ($.inArray('jqgrow', className.split(' ')) > 0) {
            var x = $(row.cells[iCol]).children("input:checked");
            if (x.length>0) {
                if ($.inArray('myAltRowClass', className.split(' ')) === -1) {
                    row.className = className + ' myAltRowClass';
                }
            }
        }
    }
}

The corresponding demo is here. You will see the following:

enter image description here

By the way if the ‘Closed’ column will be hidden everything will continue to work as before.

UPDATED 2: The answer describe how to use rowattr callback to simplify the solution and to have the best performance (in case of gridview: true).

Leave a Comment