CHanaka
CHanaka

Reputation: 502

jQuery Datatable Row Color Change Base on Cell value

I want to change row background color and text color based on cell value. My
My Html Code as Bellow

<button id="refersh">Refresh</button>
<button id="AddRow">Add New Row</button>
<table id="stdTable" class="table table-bordered table-striped" width="100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Date of birth</th>
            <th>Edit/View</th>
        </tr>
    </thead>
</table>

Data-table version is v 1.10.12. Data loading method is ajax.

Upvotes: 0

Views: 5901

Answers (2)

Gordon
Gordon

Reputation: 1651

use this createdRow function:

"createdRow": function( row, data, dataIndex ) {
                if ( data["LAYOUT"] == "N" ) {
                    $( row ).css( "background-color", "Orange" );
                    $( row ).addClass( "highlight" );
                }
            }

Upvotes: 2

Udara Kasun
Udara Kasun

Reputation: 2216

Change your script as bellow. please check "fnRowCallback" section

 var dataset = [
        [
            Id = "001",
            Name = "nn",
            Age = "Age",
            DateofBirth = "125"
        ],
         [
            Id = "001",
            Name = "nn",
            Age = "Age",
            DateofBirth = "125"
         ]
    ];    

$('#stdTable').DataTable({
        processing: true,
        serverSide: false,
        ordering: true,
        paging: true,
        searching: true,
        columns: [
           { title: "Id" },
           { title: "Name" },
           { title: "Age" },
           { title: "DateofBirth" },
           { title: "View Data" }
        ],
        columns: [
          { data: "Id" },
          { data: "Name" },
          { data: "Age" },
          { data: "DateofBirth" },
          {
              data: null,
              defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
          }
        ],
        data:dataset,
        "columnDefs": [
            {
                "targets": 0,
                "visible": false
            }
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            if (aData.Age == "20") {
                //cell background color
                $(nRow).find('td:eq(1)').css('background-color', '#ffc2c2');
            }
            else if (aData.Age == "10") {
                //row background color
                $('td', nRow).css('background-color', 'Orange');
            }
            else if (aData.Age == "25") {
                //cell text color
                 $('td', nRow).css('color', 'red');
            }
        }
    });
});

Upvotes: 0

Related Questions