Search code examples
jqueryjqgridjqgrid-asp.net

jqGrid - Conditionally format cell based off Date value


I've seen a decent amount of info surrounding the conditional formatting but can't seem to get it to work. I want to make the font of the cell red when it's value (which is a date) is in the past.

This is a general idea of what I have now:

{
              name: 'IsoDate', index: 'IsoDate', align: 'left', sorttype: 'date', datefmt: "m/d/Y",
              formatter: function (cellvalue, options, rowobject) { var now = new Date(); if (cellvalue < now) { return '<span class="error">' + cellvalue + '</span>'; } else { cellvalue; } }
          }

I can't seem to get it to work though. I've gotten it to return all red values, or all undefined values. There are some fields with no dates yet.

I'd appreciate any help! Thanks!

UPDATE:

Here is the code I used that ended up working. I actually was referencing another column for the date.

cellattr: function (rowid, val, rawObject, cm, rdata) {
                  var idate = new Date(rawObject['IsoDate']);
                  return (idate < new Date()) ? ' class = "ui-state-error-text"' : ' class = "field-validation-green"';
              }

Solution

  • It's better to use cellattr instead of custom formatter. In the case you can still use predefined formatter like formatter: "date" and just set additional style or class attribute on the selected <td> cells. For example the class ui-state-error-text seems to me good choice to make the font of the cell red. So the definition of the column could be

    {
        name: "IsoDate", sorttype: "date",
        formatter: "date", formatoptions: {newformat: "m/d/Y"},
        cellattr: function (cellvalue) {
            return (cellvalue < new Date()) ? ' class="ui-state-error-text"' : '';
        }
    }
    

    I am not sure which data have you as input and whether the code which you posted works correctly. If required you can change the above code correspond with the format of cellvalue which you have.

    See the answer, this one, this one and many other for more example of usage cellattr.