0

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.

CHanaka
  • 472
  • 5
  • 10
  • Assuming css only - see: https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text (also includes a js solution as an answer, but there are probably better duplicates for jquery only) – freedomn-m Aug 09 '18 at 11:28

2 Answers2

2

use this createdRow function:

"createdRow": function( row, data, dataIndex ) {
                if ( data["LAYOUT"] == "N" ) {
                    $( row ).css( "background-color", "Orange" );
                    $( row ).addClass( "highlight" );
                }
            }
Gordon
  • 1,633
  • 3
  • 26
  • 45
0

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');
            }
        }
    });
});
Udara Kasun
  • 2,182
  • 18
  • 25