How can I change the background color of a cell in a jqgrid custom formatter?

前端 未结 3 1917
Happy的楠姐
Happy的楠姐 2020-12-01 10:13

I can change the text color by doing this in jqgrid custom formatter:

function YNFormatter(cellvalue, options, rowObject)
{
    var color = (cellvalue == \"Y         


        
相关标签:
3条回答
  • 2020-12-01 10:27

    If you want use <span> element inside of the custom cell formatter you can return from the custom formatter

    return '<span class="cellWithoutBackground" style="background-color:' +
           color + ';">' + cellvalue + '</span>';
    

    where the style of span.cellWithoutBackground you can define for example like following

    span.cellWithoutBackground
    {
        display:block;
        background-image:none;
        margin-right:-2px;
        margin-left:-2px;
        height:14px;
        padding:4px;
    }
    

    How it works you can see live here: enter image description here

    UPDATED: The answer is old. The best practice would be to use cellattr callback in colModel instead of the usage custom formatters. Changing of background color of the cell is in general just assigning style or class attribute to the cells of the column (<td> elements). The cellattr callback defined in the column of colModel allows exactly to do this. One can still use predefined formatters like formatter: "checkbox", formatter: "currency", formatter: "date" and so on, but still change the background color in the column. In the same way the rowattr callback, which can be defined as the jqGrid option (outside of specific column of colModel), allows to assign style/class of the whole row (<tr> elements).

    More information about cellattr can be found here and here, for example. Another answer explains rowattr.

    0 讨论(0)
  • 2020-12-01 10:31

    Here

    $("#cell").setCell(Row , Column, Value, { background: '#888888'});
    

    Actually you won't even need custom formatter, if you just intend to do it for setting colors. You can even set color value from here like,

    var color = (Value == "Y") ? "green" : "red";
    $("#cell").setCell(Row , Column, Value, { background: '#888888', color: color});
    

    Happy Coding.

    0 讨论(0)
  • 2020-12-01 10:46

    Here is what I did:

    jQuery("#grid_id").jqGrid({
        ...
           colModel: [
              ...
              {name:'price', index:'price', width:60, align:"center", editable: true, formatter:myFmatter},
              ...
           ],
            afterInsertRow: function(rowId, data)
            {
                $("#grid_id").setCell(rowId, 'price', '', {'background-color':'#' + data.colorHEX});
            }
    ...
    });
    
    0 讨论(0)
提交回复
热议问题