How do i color each cell based on condition in Datatables.js after rendering the table from json data? [duplicate]
Asked Answered
M

4

5
var dataset = [];
var columns = sfdata.columns

sfdata.data.forEach(function (item,index) {
    var n2 = item.items
    dataset.push(n2)
});

$(document).ready(function() {
    $('#example').DataTable({
        data: dataset,
        columns: [
            { title: "index" },
            { title: "Name" }

        ]
    });
});

So I've made the default table in spotfire, now the question is how do i color values in a column based on conditions like (if data[2] > 10 then background-color be 'red'). Am i instantiating it wrong; how do i get it to work?

Matildamatilde answered 13/12, 2018 at 8:20 Comment(2)
Can you create snippet with sample data by editing your question?Bearskin
In the column definition, you could add class attribute or you could use the rowDrawCallback to achieve the sameKoonce
E
3

Have you tried to add createdRow to the DataTable() invocation?

$("#example").DataTable({
  "data": dataset,
  "columns": [
    { "title": "index" },
    { "title": "Name" }
  ],
  "createdRow": (row, data, dataIndex) => {
    if(data[2] >  10)
    {
      $(row).addClass("redClass");
    }
  }
});

And in CSS:

.redClass
{
  background-color: red;
}

This comes directly from the DataTables documentation.

Eglanteen answered 13/12, 2018 at 8:38 Comment(0)
R
2

$(document).ready(function() {
   var table = $('#example').DataTable({
      'ajax': 'https://api.myjson.com/bins/qgcu',
     "columnDefs": [ {
        "targets":3,
        "render": function ( data, type, row, meta ) {
         var highlight="";
         if(data==5407 || data == 1314)highlight="link"; // Put your conditions here
          return '<span class="'+highlight+'"><i class="fa fa-heart" aria-hidden="true"></i> '+data+'</span>';
        }
  } ],
  "initComplete": function(settings, json) {
    $(".link").parent().addClass("link");
  }
   });  
  
});
.link{
  color:white;
  background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script>
<script src="https://cdn.rawgit.com/ashl1/datatables-rowsgroup/fbd569b8768155c7a9a62568e66a64115887d7d0/dataTables.rowsGroup.js"></script>
<link href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">
<h3>jQuery DataTables - ROWSPAN in table body TBODY</h3>

<hr><br>
    
<table id="example" class="display" cellspacing="0" width="100%">
   <thead>
      <tr>
         <th>Name</th>
         <th>Position</th>
         <th>Office</th>
         <th>Extn.</th>
         <th>Start date</th>
         <th>Salary</th>
      </tr>
   </thead>
   <tfoot>
      <tr>
         <th>Name</th>
         <th>Position</th>
         <th>Office</th>
         <th>Extn.</th>
         <th>Start date</th>
         <th>Salary</th>
      </tr>
   </tfoot>
</table>

Use column.render to achieve this. Hope this helps.

Ruvolo answered 13/12, 2018 at 8:56 Comment(5)
Thanks . But i'm not able to pull data with the "Ajax" attribute.Matildamatilde
Use dataset instead, i fetched data from remote location.Ruvolo
One more thing , do you know how do i add icons inside a cell. i tried using bootstrap css but its not working, if you have anything working can you pass me on the CDN and how did you do it?Matildamatilde
@ShricharanArumugam use font awesomeRuvolo
@ShricharanArumugam I updated answer with icon please checkRuvolo
M
2

if you want to style a specific cell based on a column you have to use columnDefs with render option as a callback with a target which refers to the column you want to control the cells in (you can take look here also).

so the code should look like that:

  var dataSet = [
["Tiger Nixon", 1, "Edinburgh", "5421", "2011/04/25", "$320,800"],
["Garrett Winters", 12, "Tokyo", "8422", "2011/07/25", "$170,750"],
["Ashton Cox", 4, "San Francisco", "1562", "2009/01/12", "$86,000"],
["Cedric Kelly", 5, "Edinburgh", "6224", "2012/03/29", "$433,060"],
["Airi Satou", 23, "Tokyo", "5407", "2008/11/28", "$162,700"],
["Brielle Williamson", 54, "New York", "4804", "2012/12/02", "$372,000"],
["Herrod Chandler", 2, "San Francisco", "9608", "2012/08/06", "$137,500"]
  ];

var columnDefs = [{
   title: "Name"
  }, {
    title: "Position"
  }, {
    title: "Office"
  }, {
    title: "Extn."
  }, {
    title: "Start date"
  }, {
    title: "Salary"
  }];

var myTable;

myTable = $('#example').DataTable({
   data: dataSet,
   columns: columnDefs,
   columnDefs: [{
     targets: 1, // this means controlling cells in column 1
     render: function(data, type, row, meta) { 
       if (data > 10) { // here is your condition
         return '<div class="red-color">' + data + '</div>';
       } else {
         return data;
       }
     }
   }]
 });

and here is a working snippet

Mckenney answered 13/12, 2018 at 9:16 Comment(2)
how do i give conditions for multiple columns?Matildamatilde
columnDefs takes an array of objects, you can consider each object represent a column, you just have to change the target number. i have updated the snippet you can take a look hereMckenney
B
1

You can use columnDefs to achieve what you want.

targets is the the column number you want to filter out and render is the event which will be triggered when that column is going to be rendered. So, you have the data you want, based on the data you can filter out the result and apply the background-color.

Here is the demo.

var dataSet = [{
  index: 1,
  name: "test"
}, {
  index: 2,
  name: "test2"
}, {
  index: 3,
  name: "test3"
}];


$(document).ready(function() {
  $('#example').DataTable({
    data: dataSet,
    columns: [{
        data: "index"
      },
      {
        data: "name"
      }
    ],
    columnDefs: [{
     targets : [0],
      render: function(data, type, row) {
      
        if(row.index>2){
          return "<div style='background-color:red'>"+data+"<div>";
        }
        return data;
      }
    }]
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="example" class="display" width="100%"></table>
Bearskin answered 13/12, 2018 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.