Xavier
Xavier

Reputation: 257

Change color of table cell in javascript based on other cell's value

I am displaying a table on the webpage as follows:

ID  | Val      | Num
ABC | Value1   | 1
ABC | Value1   | 0.8
CDB | Value 2  | 0.5

I want that if the cell value in Num column for that row is between 1 and 0.8, then the background color of the corresponding Val column's cell should be red, if between 0.7 to 0.5 then orange, and below it yellow.

I'm using DataTables

Below is my js code:

for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
          if (col_id === 2) {

              row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
          }
          else {
              row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
          }
            }

            row_html += "</tr>";
            $('#' + el + '-table tbody').append(row_html);
          }

          $('#' + el + '-table').DataTable(datatables_options);

I tried to add the background color to the cell using the style.backgroundColor but I don't think it's working. I added this inside the for loop:

if (col_id === 1) {
              if (parseFloat(csv_data[row_id][2]) <= 1 && parseFloat(csv_data[row_id][2]) > 0.7)
              {
              row_html.style.backgroundColor = 'ec8e8e'
              }
          }

But it's not working. Could anybody tell me how to do it?? Thanks!

UPDATE:

My csvToHtml.js file:

var CsvToHtmlTable = CsvToHtmlTable || {};

CsvToHtmlTable = {
    init: function (options) {

      options = options || {};
      var csv_path = options.csv_path || "";
      var el = options.element || "table-container";
      var allow_download = options.allow_download || false;
      var csv_options = options.csv_options || {};
      var datatables_options = options.datatables_options || {};
      var custom_formatting = options.custom_formatting || [];

      $("#" + el).html("<table class='table table-striped table-condensed' id='" + el + "-table'></table>");

      $.when($.get(csv_path)).then(
        function(data){      
          var csv_data = $.csv.toArrays(data, csv_options);

          var table_head = "<thead><tr>";

          for (head_id = 0; head_id < csv_data[0].length; head_id++) { 
            table_head += "<th>" + csv_data[0][head_id] + "</th>";
          }

          table_head += "</tr></thead>";
          $('#' + el + '-table').append(table_head);
          $('#' + el + '-table').append("<tbody></tbody>");

          for (row_id = 1; row_id < csv_data.length; row_id++) { 
            var row_html = "<tr>";

            //takes in an array of column index and function pairs
            if (custom_formatting != []) {
              $.each(custom_formatting, function(i, v){
                var col_idx = v[0]
                var func = v[1];
                csv_data[row_id][col_idx]= func(csv_data[row_id][col_idx]);
              })
            }

              for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
          if (col_id === 2) {

              row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
          }
          else {
              row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
          }


            }

            row_html += "</tr>";
            $('#' + el + '-table tbody').append(row_html);
          }

          $('#' + el + '-table').DataTable(datatables_options);

          if (allow_download)
            $("#" + el).append("<p><a class='btn btn-info' href='" + csv_path + "'><i class='glyphicon glyphicon-download'></i> Download as CSV</a></p>");
        });
    }
}

My index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>CSV to HTML Table</title>



<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/dataTables.bootstrap.css" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

   <h2>CSV to HTML Table</h2>

  <div id='table-container'></div>

</div><!-- /.container -->


<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.csv.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="js/csv_to_html_table.js"></script>


<script type="text/javascript">
  function format_link(link){
    if (link)
      return "<a href='" + link + "' target='_blank'>" + link + "</a>";
    else
      return "";
  }
  CsvToHtmlTable.init({
    csv_path: 'data/fatty_acid_profiles.csv',
    element: 'table-container', 
    allow_download: true,
    csv_options: {separator: ','},
    datatables_options: {"paging": false},
    custom_formatting: [[2, format_link]]
  });
</script>

Upvotes: 2

Views: 3567

Answers (1)

Yogen Darji
Yogen Darji

Reputation: 3300

You can append row_html with $(row_html) and apply css to that with your condition.

Here color will be based on your condition.

 $('#' + el + '-table tbody').append($(row_html).css('background',color));

Check below sample to get more idea

$(document).ready(function() {
  $('#example').dataTable();

  var val = 0.1;

  var row_html = "<tr>";
  row_html += "<td>ADD</td><td>val 4</td><td>" + val + "</td>";
  row_html += "</tr>";
  var color = "red"; // can be hex value, #ededed

  if (val > 0.7) {
    color = "orange";
  } else if (val < 0.4) {
    color = "yellow";
  }

  $('#example').append($(row_html).css("background-color", color));



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script  src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">


<body>
  <div class="container">

    <table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example">
      <thead>
        <tr>
          <th>ID</th>
          <th>Val</th>
          <th>Num</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>ABC</td>
          <td>Value 1</td>
          <td>0.5</td>

        </tr>
        <tr>
          <td>BBC</td>
          <td>Value 2</td>
          <td>0.8</td>
        </tr>
        <tr>
          <td>CBC</td>
          <td>Value 3</td>
          <td>1</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

Upvotes: 1

Related Questions