0

I have the below script that dynamically generates a table based on an array of objects that the server is feeding me that I got from Here (hopefully I got the anchor tag right, here should be a link).

// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(myList) {
 var columns = addAllColumnHeaders(myList);
  for (var i = 0 ; i < myList.length ; i++) {
     var row$ = $('<tr/>');
     for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
         var cellValue = myList[i][columns[colIndex]];
         if (cellValue == null) { cellValue = ""; }
\\This is where I want to put the code that compares cellValue and applies 
\\the class
         row$.append($('<td/>').html(cellValue));
     }
     $("#Jsontable").append(row$);
 }
 }
function addAllColumnHeaders(myList)
{
 var columnSet = [];
 var headerTr$ = $('<tr/>');
 for (var i = 0 ; i < myList.length ; i++) {
     var rowHash = myList[i];
     for (var key in rowHash) {
         if ($.inArray(key, columnSet) == -1){
             columnSet.push(key);
             headerTr$.append($('<th/>').html(key));
         }
     }
 }
 $("#Jsontable").append(headerTr$);
 return columnSet;      
}

I cannot figure out how to add a class to each td based on comparing the value of cellvalue to a goal value where it is classed as .red if it is higher and .green if it is not. My comment in the above code is where I believe the if/then should appear, but my kung fu is no good here.

RobG
  • 142,382
  • 31
  • 172
  • 209
Corey
  • 11
  • 4

1 Answers1

0

Something like:

row$.append($('<td/>').html(cellValue).addClass(cellValue > goal ? 'red' : 'green'));
James
  • 1,138
  • 9
  • 13
  • The idea seems sound, but it is applying it to the whole row, not to the cell. As it iterates through I think it appends a td each iteration so I thought "$('').last().addClass(cellValue > goal ? 'red' : 'green');" might do the trick, but no luck. – Corey May 03 '18 at 20:18
  • In that case, maybe: `var $td = $('').html(cellValue); if(colIndex == columns.length-1){ $td.addClass(cellValue > goal ? 'red' : 'green'); } $row.append( $td );` ? – James May 03 '18 at 20:31