Javascript cell color according to math - javascript

I have an html table with numbers. For example:
Col1 Col2 Col3
5 3 1
1 2 1
10 3 2
And I want to use Javascript in order each cell has a specific color background according to the following math:
if one of the three columns (for each row) is greater than the sum of the other 2 columns
for example:
Col1 > Col2 + Col3 => bkg color: #000
Col2 > Col1 + Col3 => bkg color: #333
Col3 > Col1 + Col3 => bkg color: #666
Can I do it with Javascript? Can anyone help with the code?

Here's something for you (http://jsfiddle.net/AbnCz/3/). This doesn't scale that well as an algo, but works as per your requirements. If you end up adding more rows/cols, add the appropriate colors in the colors array.
> update: made a perf update to cache the sum as opposed to determining it through each cell traversal
HTML
<table id="dataTable">
<tr>
<td>20</td>
<td>50</td>
<td>70</td>
</tr>
<tr>
<td>40</td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>60</td>
</tr>
</table>
Javascript
var colors = ["#000","#333","#666"];
var t = document.getElementById('dataTable');
var rows = t.getElementsByTagName('tr'), row, cells, tgtCell, rowSum, othersSum;
// let's go through the rows
for(var r=0; r<rows.length; r++){
row = rows[r];
cells = row.getElementsByTagName('td');
rowSum = 0;
// lets get the sum for the row.
// we'll subtract each cell from it to get the remaining sum.
for(var _c=0; _c<cells.length; _c++){
rowSum += parseInt(cells[_c].textContent,10);
}
// let's go through the cells
for(var c=0; c<cells.length; c++){
tgtCell = cells[c];
tgtVal = parseInt(tgtCell.textContent, 10);
othersSum = rowSum - tgtVal;
// if the target is greater than the remaining sum, style it
if(tgtVal > othersSum){
tgtCell.style.backgroundColor = colors[c % colors.length];
}
}
}

Try this :
HTML:
<table id="dataTable">
<tr>
<td>3</td>
<td>5</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>16</td>
<td>13</td>
<td>2</td>
</tr>
</table>
JAVASCRIPT :
var table = document.getElementById('dataTable'), activeCells
row = table.getElementsByTagName('tr'),
cell = table.getElementsByTagName('td');
var colorArray = new Array('red', 'blue', 'yellow');
//loop through all rows
for ( var i = 0; i < row.length; ++i) {
//get cells currently being read
activeCells = row[i].getElementsByTagName('td');
//prepare storage
var cellArray = new Array(),
newCellArray = new Array(),
cellElementArray = new Array(),
sum = 0;
//loop through active cells
for ( var x = 0; x < activeCells.length; ++x ) {
var currentCell = activeCells[x],
cellVal = parseInt( currentCell.innerHTML );
cellArray[x] = cellVal;
newCellArray[x] = cellVal;
cellElementArray[x] = currentCell;
}
//loop through Cell Array
for ( var y = 0; y < cellArray.length; ++y ) {
newCellArray.splice(y, 1);
for ( var z = 0; z < newCellArray.length; ++z ) {
sum += newCellArray[z];
}
newCellArray = [];
for ( var n = 0; n < cellArray.length; ++n ) {
newCellArray[n] = cellArray[n];
}
console.log( sum);
if ( cellArray[y] > sum ) {
console.log( 'in');
cellElementArray[y].style.backgroundColor = colorArray[y];
}
sum = 0;
}
}
An additional feature that I implemented is that this is dynamic. Try to increase the number of cells and it will still calculate.
And please change the colorArray according to your preference. It is by column ordered. something like var colorArray = new Array('#000','#333','#667');
jsfiddle demo: http://jsfiddle.net/aVqCU/

I haven't tested this code myself. But it should be something like this:
var table = document.getElementById("table"); //Replace "table" with the id of your table in the HTML
var table = document.getElementById("table"); //Replace "table" with the id of your table in the HTML
for (var i = 0, row; row = table.rows[i]; i++) //iterate through rows
{
var cell1 = row.cells[0];
var cell2 = row.cells[1];
var cell3 = row.cells[2];
if(parseFloat(cell1.innerHTML) > (parseFloat(cell2.innerHTML) + parseFloat(cell3.innerHTML)))
{
cell1.style.backgroundColor = "#000";
}
if(parseFloat(cell2.innerHTML) > parseFloat(cell3.innerHTML) + parseFloat(cell1.innerHTML))
{
cell2.style.backgroundColor = "#333";
}
if(parseFloat(cell3.innerHTML) > parseFloat(cell2.innerHTML) + parseFloat(cell1.innerHTML))
{
cell3.style.backgroundColor = "#666";
}
}
You may need to use parseInt or parseFloat on the row.cells to convert the text to a number.

Related

how to make JavaScript cell take full row width

I have a table which takes data from an array. My problem is that I do not know how to make it so that the cell takes the whole row if the objects in the array have a value of zero. If it has a value greater than zero, 2 cells will be displayed one with an item name and another with its value. Any help is much appreciated.
//breaks loop if x is == to counters array
if (this.state.counters.length == x) {
break;
}
const info = this.state.counters[x]["text"];
const quantity = this.state.counters[x]["value"];
console.log(info, quantity);
//creates rows based on input
var table = document.getElementById("myList");
var row = table.insertRow(1);
document.getElementById("thTitle").style.maxWidth = "100px";
if (quantity <= 0) {
var itemCell = row.insertCell(0);
itemCell.innerHTML = info;
} else {
var itemCell = row.insertCell(0);
var quantityCell = row.insertCell(1);
itemCell.innerHTML = info;
itemCell.style.minWidth = "100px";
quantityCell.innerHTML = quantity;
}
This is my output:
put this in:
if (quantity <= 0) {
var itemCell = row.insertCell(0);
itemCell.innerHTML = info;
// this line
itemCell.setAttribute('colspan', '2');
}
there is the attribute colspan to td tag that the number is the number of rows he stretched on.
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td colspan="2">Sum: $180</td>
</tr>
</table>
//In Js just add
itemCell.setAttribute('colspan', '2');
when the quantity <= 0

How to highlight a table row with the smallest value in a certain column using javascript

Supposed that I have a table like this on a webpage with the id ='table':
Name Age Money(USD) DATE
A 19 4 2019-03-11 16:15:35
B 20 0 2019-03-11 16:16:37
C 27 3 2019-03-13 04:15:43
D 34 0 2019-03-13 04:16:57
Could you help me find the FIRST SMALLEST VALUE IN THE MONEY COLUMN, which is 0 for B in the Column1 and HIGHLIGHT the whole table row for B, using javascript without using any library and any button onClicking?
Note: I have searched around and just been unlucky enough to find the correct answer to my problem.
Thanks.
UPDATE:I just got a piece of javacript like this to get the first smallest value and print it out, but not be able to highlight the whole row with it
var table = document.getElementById("table"), minVal;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){minVal = table.rows[i].cells[2].innerHTML; }
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
}
}
document.getElementById("val").innerHTML = " Minimum Value = "+minVal;
console.log(maxVal);
var table = document.getElementById("table"), minVal, minI;
for(var i = 1; i < table.rows.length; i++){
if(i === 1){
minVal = table.rows[i].cells[2].innerHTML;
}
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minI = i;
}
}
table.rows[i].cells[2].innerHTML = '<span style="background:red">' + table.rows[minI].cells[2].innerHTML + '</span>';
Something like that.
var table = document.getElementById("table");
var minVal = undefined;
for(var i = 1; i < table.rows.length; i++)
{
if(i === 1){
minVal = table.rows[i].cells[2];
}
else if(minVal.innerHTML > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2];
}
}
minVal.parentElement.style.background="yellow";
There are two things you need to do:
Convert innerHTML to a number using +
Keep track of the row number while looping.
This is the code
var table = document.getElementById("table"), minVal;
let minRow = 1;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){
minVal = +table.rows[i].cells[2].innerHTML;
}
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minRow = i;
}
}
let row = table.rows[minRow];
row.style.backgroundColor = 'red';
This simply keeps track of the minimum row, and lets you hang your formatting off of that:
const highlightLowest = () => {
var rows = table.rows;
var minRow = rows[0]
for (var i = 1; i < rows.length; i++){
rows[i].classList.remove('highlight')
if (Number(rows[i].cells[2].innerHTML) < Number(minRow.cells[2].innerHTML)) {
minRow = rows[i]
}
}
minRow.classList.add('highlight')
}
tr.highlight td {background-color: yellow}
<table id="table">
<tr><td>A</td><td>19</td><td>4</td><td>2019-03-11 16:15:35</td></tr>
<tr><td>B</td><td>20</td><td>0</td><td>2019-03-11 16:16:37</td></tr>
<tr><td>C</td><td>27</td><td>3</td><td>2019-03-13 04:15:43</td></tr>
<tr><td>D</td><td>34</td><td>0</td><td>2019-03-13 04:16:57</td></tr>
</table>
<hr />
<button onClick="highlightLowest()">Highlight</button>
Here you go. The function 'highlight' takes the column that you want to base your highlighting upon as an argument.
// Get your table's headers
headers = document.querySelectorAll('#table tbody tr th')
// Get your table's headers
rows = document.querySelectorAll('#table tbody tr')
// Declaring function that takes wanted column as argument
highlight = (colName) =>{
let min = 0;
for(i=0;i<headers.length;i++){
if(headers[i].innerText == colName){
for(j=1;j<rows.length;j++){
value = parseInt(rows[j].children[i].innerHTML);
if(j == 1){
min = value;
}
if(value < min){
rows[j].style.backgroundColor = "yellow"
break;
}
}
}
}
}
<table id="table">
<tbody><tr>
<th>Test 1</th>
<th>Test 2</th>
<th>Test 3</th>
</tr>
<tr>
<td>7</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td>12</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>15</td>
<td>89</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>8</td>
</tr>
</tbody></table>
<input type='text' id='col'>
<button onclick=highlight(document.getElementById('col').value)>Highlight based on input column</button>

How to apply CSS to table cell depending on conditions

I have a table with 10 rows and data is
ABC XYZ 30% (ABC)
ABC MNO 91% (XYZ)
var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var data = col.innerText;
var data1 = data.split(" ");
if(data1[0] == "91%"){
row.cells[j].css( "color", "red" );
}
}
}
I want to add red color to the cells which are above 90%. How to do it.
I know in back-end we can do it but now I am using only html and CSS.
Slight variation in your code can make it works
var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var data = col.innerText;
// replace % symbol, parse and compare with number
if (+data.replace('%', '') > 90) {
// update style property of cell
col.style.color = "red";
}
}
}
<table id="table2">
<tr>
<td>ABC</td>
<td>XYZ</td>
<td>30%</td>
<td>(ABC)</td>
</tr>
<tr>
<td>ABC</td>
<td>MNO</td>
<td>91%</td>
<td>(XYZ)</td>
</tr>
</table>
If a single column contains the entire string then do something like this
var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
// get the percentage value from string
var data = col.innerText.match(/(\d+(?:\.\d+)?)%/);
// check match found or not then parse and compare with number
if (data && +data[1] > 90) {
// update style property of cell
col.style.color = "red";
}
}
}
<table id="table2">
<tr>
<td>ABC XYZ 30% (ABC)</td>
</tr>
<tr>
<td>ABC MNO 91% (XYZ)</td>
</tr>
</table>

How to get min and max number from selected rows of table?

This refers to my previous question.
How to highlight/color multiple rows on selection?
<table id="toppings" border="1" cellpadding="2">
<tr id="id1">
<td>3</td>
<td>row12</td>
<td>row13</td>
</tr>
<tr id="id2">
<td>12</td>
<td>row22</td>
<td>row23</td>
</tr>
<tr id="id3">
<td>15</td>
<td>row32</td>
<td>row33</td>
</tr>
<tr id="id4">
<td>22</td>
<td>row42</td>
<td>row43</td>
</tr>
<tr id="id5">
<td>23</td>
<td>row52</td>
<td>row53</td>
</tr>
<tr id="id6">
<td>55</td>
<td>row62</td>
<td>row63</td>
</tr>
</table>
Javascript Code:
//Get list of rows in the table
var table = document.getElementById("toppings");
var rows = table.getElementsByTagName("tr");
var selectedRow;
//Row callback; reset the previously selected row and select the new one
function SelectRow(row) {
if (selectedRow !== undefined) {
selectedRow.style.background = "#d8da3d";
}
selectedRow = row;
selectedRow.style.background = "white";
}
//Attach this callback to all rows
for (var i = 0; i < rows.length; i++) {
var idx = i;
rows[idx].addEventListener("click", function(){SelectRow(rows[idx])});
}
But this time I have added an event to table for row selection and trying to get min and max value from selected rows (first column). Like above table, if I select middle four rows, i should get min = 12 and max = 23. How can this be implemented?
You can have two functions. I show the getMinValueExample().
function getMinValueExample(rows){
var minValue = null;
for (var i = 0; i < rows.length; i++){
var firstTd = rows[i].getElementsByTagName('td')[0];
var currentValue = parseInt(firstTd.innerHTML);
if(minValue == null || minValue > currentValue)
minValue = currentValue;
}
return minValue;
}
(not test so can contain some type errors but you should get the idea)
So if you call this after you've declared rows it returns the min value.
And if you call this one you get the max value
function getMaxValueExample(rows){
var maxValue = null;
for (var i = 0; i < rows.length; i++){
var firstTd = rows[i].getElementsByTagName('td')[0];
var currentValue = parseInt(firstTd.innerHTML);
if(maxValue == null || maxValue < currentValue)
maxValue = currentValue;
}
return maxValue;
}

html table: adding a class to the highest value of each column

Is there any way to find the highest value of each column (in a html table) and to add a class to it using js or jQuery?
Note: the table is build with <thead> and <tbody>
The table looks like this:
<table>
<thead>
<tr>
<th class="age">age</th>
<th class="success">success</th>
<th class="weight">weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>30%</td>
<td>70.5kg</td>
</tr>
<tr>
<td>30</td>
<td>40%</td>
<td>80.9kg</td>
</tr>
<tr>
<td>13</td>
<td>60%</td>
<td>20.53kg</td>
</tr>
<tr>
<td>44</td>
<td>80.44%</td>
<td>20kg</td>
</tr>
</tbody>
</table>
Codepen
FIDDLE - http://jsfiddle.net/tariqulazam/esfj9/
JAVASCRIPT
var $table = $("#mytable");
$table.find("th").each(function(columnIndex)
{
var oldValue=0, currentValue=0, $elementToMark;
var $trs = $table.find("tr");
$trs.each(function(index, element)
{
$(this).find("td:eq("+ columnIndex +")").each(function()
{
if(currentValue>oldValue)
oldValue = currentValue;
currentValue = parseFloat($(this).html());
if(currentValue > oldValue)
{
$elementToMark = $(this);
}
if(index == $trs.length-1)
{
$elementToMark.addClass("highest");
}
});
});
});​
​CSS
.highest{
color:Red;
}​
​Here's the JSFiddle I made:JSFiddle
Here's the function, using jQuery
function MarkLargest() {
var colCount = $('th').length;
var rowCount = $('tbody tr').length;
var largestVals = new Array();
for (var c = 0; c < colCount; c++) {
var values = new Array();
for (var r = 0; r < rowCount; r++) {
var value = $('tbody tr:eq(' + r + ') td:eq(' + c + ')').text();
value = value.replace("%", "").replace("kg", "");
values.push(value);
}
var largest = Math.max.apply(Math, values);
largestVals.push(largest);
$('tbody tr').each(function() {
var text = $(this).find('td:eq(' + c + ')').text();
text = text.replace("%", "").replace("kg", "");
if (text == largest) {
$(this).find('td:eq(' + c + ')').addClass("max");
}
});
}
return largestVals[column];
}
$(function() {
MarkLargest();
})​
OK, my first answer only returned the highest value of a particular column. I think this is what you are looking for (in vanilla JavaScript):
HTML
<table id="mytable">
<thead>
<tr>
<th class="age">age</th>
<th class="sucess">sucess</th>
<th class="weight">weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>30%</td>
<td>70.5kg</td>
</tr>
<tr>
<td>30</td>
<td>40%</td>
<td>80.9kg</td>
</tr>
<tr>
<td>13</td>
<td>60%</td>
<td>20.53kg</td>
</tr>
<tr>
<td>44</td>
<td>80.44%</td>
<td>20kg</td>
</tr>
</tbody>
</table>
JavaScript
function markColumnCeilings ( table ) {
if ( table === null ) return;
var thead = table.tHead,
tbody = table.tBodies[0],
rowCount = tbody.rows.length,
colCount = thead.rows[0].cells.length,
maxvalues = new Array( colCount ),
maxCells = new Array( colCount ),
i = rowCount - 1,
j = colCount - 1,
cell, value;
// Loops through rows/columns to get col ceilings
for ( ; i > -1 ; i-- ) {
for ( ; j > -1 ; j-- ) {
cell = tbody.rows[ i ].cells[ j ];
value = parseFloat( cell.innerHTML );
if ( value.toString() === "NaN" ) continue;
if ( value > ( maxvalues[ j ] === undefined ? -1 : maxvalues[ j ] ) ) {
maxvalues[ j ] = value;
maxCells[ j ] = i + "," + j;
}
}
j = colCount - 1;
}
// Set classes
for ( ; j > -1 ; j-- ) {
tbody.rows[ maxCells[ j ].split( "," )[ 0 ] ]
.cells[ maxCells[ j ].split( "," )[ 1 ] ]
.setAttribute( "class", "max" );
}
}
var table = document.getElementById( 'mytable' );
markColumnCeilings( table );
CSS
td.max { font-weight: bold; }
Fiddle: http://jsfiddle.net/kboucher/cH8Ya/
I have modified the function of #sbonkosky to be able to manage various tables. In my case I have various tables and it was mixing values of all them.
function GetLargestValueForColumn(table) {
let colCount = $('table:eq('+ table +') th').length;
let rowCount = $('table:eq('+ table +') tbody tr').length;
let largestVals = new Array();
for (let c = 0; c < colCount; c++) {
let values = new Array();
for (let r = 0; r < rowCount; r++) {
let value = $('table:eq('+ table +') tbody tr:eq(' + r + ') td:eq(' + c + ')').text();
value = value.replace("%", "").replace("kg", "").replace(" ", "").replace(".", "");
values.push(value);
}
let largest = Math.max.apply(Math, values);
largestVals.push(largest);
$('tbody tr').each(function() {
let text = $(this).find('td:eq(' + c + ')').text();
text = text.replace("%", "").replace("kg", "").replace(" ", "").replace(".", "");
if (text == largest) {
$(this).find('td:eq(' + c + ')').addClass("max");
}
});
}
return
}
$(function() {
$('table').each(function(table) {GetLargestValueForColumn(table)});
})

Categories