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

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)});
})

Related

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>

merging selected cells of a dynamically created table using jquery

I have created a dynamic table based on user input and selecting the cells using jquery. Now i want to merge the selected cells using jquery.
Thanks, Regards.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.border = '1';
table.id = 'myTable';
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
$(document).ready(function () {
$('#myTable td').click(function () {
var selected = $(this).hasClass('highlited');
$('#myTable tr').removeClass('highlited');
if (!selected)
$(this).addClass('highlited');
});
});
});
}
UI :
on clicking the merge button selected cells should be merged.
You want to highlight TD after dynamically created.
Part 1:
Step 1 : Create dynamically table
Step 2 : Apply click event to each td
Part 2:
Merge td who has highlited class in each tr;
Please check below code:
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.border = '1';
table.id = 'myTable';
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
$('#myTable td').each(function () {
$(this).click(function () {
var selected = $(this).hasClass('highlited');
$('#myTable tr').removeClass('highlited');
if (!selected) $(this).addClass('highlited');
});
});
};
function mergeCell() {
$('#myTable tr').each(function (e) {
var oldTDLength = $(this).find('td').length;
for(xTD=0; xTD<oldTDLength;xTD++)
{
crrTD = $(this).find('td:eq(' + xTD + ')');
crrTDNext = $(this).find('td:eq(' + xTD + ')').next();
var colSpan = 1;
while (((crrTD.hasClass('highlited')) && (crrTD.hasClass('highlited') == crrTDNext.hasClass('highlited')))) {
var tempCell = crrTDNext;///store old cell in temp
crrTDNext = crrTDNext.next();///get next
tempCell.remove();///remove next highlited cell
colSpan++;
xTD++;//to skip merged cell
}
if (colSpan > 1) crrTD.attr('colSpan', colSpan);
}//td loop
});//tr loop
}
.highlited{background-color:#ffd800;color:#ff0000}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" value="5" /></td>
<td><input type="text" id="txtcols" value="5" /></td>
<td><button onclick="CreateTable()">Create Table</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
<button onclick="mergeCell()">Merge Highlight Cell</button>
var StartTD = null;
var StartIndex = null;
var EndTD = null;
var EndIndex = null;
$().ready(function() {
$("td").unbind("mousedown").bind("mousedown", function() {
$("table td").css("background-color", "");
StartTD = $(this);
var y = $(this).index();
var x = $(this).parent().index();
StartIndex = {
x: x,
y: y
};
});
$("td").unbind("mouseup").bind("mouseup", function() {
EndTD = $(this);
var y = $(this).index();
var x = $(this).parent().index();
EndIndex = {
x: x,
y: y
};
SelectTD(StartIndex, EndIndex, "green");
});
$("#btMerge").click(function() {
MergeCell(StartIndex, EndIndex);
MergeCell(EndIndex, StartIndex);
});
});
function SelectTD(StartIndex, EndIndex, Color) {
var MinX = null;
var MaxX = null;
var MinY = null;
var MaxY = null;
if (StartIndex.x < EndIndex.x) {
MinX = StartIndex.x;
MaxX = EndIndex.x;
} else {
MinX = EndIndex.x;
MaxX = StartIndex.x;
};
if (StartIndex.y < EndIndex.y) {
MinY = StartIndex.y;
MaxY = EndIndex.y;
} else {
MinY = EndIndex.y;
MaxY = StartIndex.y;
};
StartIndex = {
x: MinX,
y: MinY
};
EndIndex = {
x: MaxX,
y: MaxY
};
for (var i = MinX; i <= MaxX; i++) {
for (var j = MinY; j <= MaxY; j++) {
var SelectTR = $("table tr").eq(i);
$("td", SelectTR).eq(j).css("background-color", Color);
}
}
}
function MergeCell(StartIndex, EndIndex) {
var Colspan = null;
var Rowspan = null;
console.log(StartIndex, EndIndex)
Rowspan = EndIndex.x - StartIndex.x + 1;
Colspan = EndIndex.y - StartIndex.y + 1;
var IndexTR = $("table tr").eq(StartIndex.x);
$("td", IndexTR).eq(StartIndex.y).attr("colspan", Colspan).attr("rowspan",
Rowspan);
for (var i = StartIndex.x; i <= EndIndex.x; i++) {
for (var j = StartIndex.y; j <= EndIndex.y; j++) {
if (i == StartIndex.x && j == StartIndex.y) continue;
var SelectTR = $("table tr").eq(i);
$("td", SelectTR).eq(j).hide();
}
}
}
table {
width: 80%;
}
table td {
border: 1px solid #97B4D1;
text-align: center;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
<input id="btMerge" type="button" value="Merge cells" />

Javascript insert row into table after row with certain id

I have a table where each row has its unique id. Say there are rows with id='id25' and id='id26'. I need to insert a new row after row with id='id25'. I am using Vanilla JS without jQuery.
I have tried this:
var refElement = document.getElementById('id'+id);
var newrow = document.createElement("tr");
if (refElement) {
refElement.insertBefore(newrow, refElement.nextSibling);
}
but it throws me an error saying
Failed to execute 'insertBefore' on 'Node'
The node before which the new node is to be inserted is not a child of this node.
I know how to insert rows into top or bottom of the table but now I have an id as a reference to a particular row.
Any suggestions would be welcome
You want to insert into the refElement's parent, not refElement itself:
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
// -------^^^^^^^^^^^
var id = 1;
var refElement = document.getElementById('id' + id);
var newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row</td>";
if (refElement) {
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
}
<table>
<tbody>
<tr id="id1"><td>refElement</td></tr>
<tr><td>original next sibling</td></tr>
</tbody>
</table>
(And yes, for anyone wondering, it'll work even if the refElement is the last row in the table.)
Inserting five rows per comment:
var id = 1;
var refElement = document.getElementById('id' + id);
var n, newrow;
if (refElement) {
for (n = 0; n < 5; ++n) {
newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row #" + n + "</td>";
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
}
}
<table>
<tbody>
<tr id="id1">
<td>refElement</td>
</tr>
<tr>
<td>original next sibling</td>
</tr>
</tbody>
</table>
Note the order in which those appeared. If you want them in 0 - 4 order instead:
var id = 1;
var refElement = document.getElementById('id' + id);
var n, newrow;
if (refElement) {
for (n = 0; n < 5; ++n) {
newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row #" + n + "</td>";
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
refElement = refElement.nextSibling; // *** This is the change
}
}
<table>
<tbody>
<tr id="id1">
<td>refElement</td>
</tr>
<tr>
<td>original next sibling</td>
</tr>
</tbody>
</table>
function addRowAfter(rowId){
var refElement = document.getElementById('id'+id);
var newrow= document.createElement('tr');
refElement.parentNode.insertBefore(newrow, refElement.nextSibling );
return newRow;
}
Check this.

Loop through html cells and perform a function if conditionals are met

var tableBody = document.getElementById("firstTableBody"),
secondTable = document.getElementById("secondTable");
function insertRow() {
var Row = tableBody.insertRow();
for (var c = 0; c < 3; c += 1) {
Row.insertCell(c);
}
var Fruits = ["Apples", "Oranges", "Strawberries"],
random_Fruits = Fruits[Math.floor(Math.random() * Fruits.length)];
Row.cells[0].innerHTML = random_Fruits;
Row.cells[1].innerHTML = 100;
var Sellbtn = document.createElement('button');
Sellbtn.innerHTML = "Sell"
Sellbtn.onclick = function Sell() {
if (secondTable.rows.length < 1) {
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
} else {
for (var i = 0; i < secondTable.rows.length; i += 1) {
if (secondTable.rows[i].cells[0].innerHTML === this.parentNode.parentNode.cells[0].innerHTML) {
secondTable.rows[i].cells[1].innerHTML = +this.parentNode.parentNode.cells[1].innerHTML;
} else {
var Rowz = secondTable.insertRow();
for (var k = 0; k < 4; k += 1) {
Rowz.insertCell(k);
}
Rowz.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Rowz.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
}
}
Row.cells[2].appendChild(Sellbtn);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
<th>
<button onclick="insertRow()">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
</tbody>
</table>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
</body>
I insert a row with randomly inserted fruit name and a dynamically added button called sell. When I click on sell it should check if the fruit name of that row exists in the second table or not if so then it should add the sold amount in the row that's in the second table that has the same name. If not then simply add a new row in the second table with the name and sold amount. jQuery is ok.
here is a possible solution, replacement for your function Sell()
Sellbtn.onclick = function Sell() {
var found = false,
rows = secondTable.rows,
numrows = rows.length,
tofind = this.parentNode.parentNode.cells[0].innerHTML,
foundin,
numToAdd = parseInt(this.parentNode.parentNode.cells[1].innerHTML),
num,
x;
for(x=0;x<numrows;x++){
if(rows[x].cells[0].innerHTML === tofind){
found = true;
foundin = x;
}
}
if(found){
num = parseInt(rows[foundin].cells[1].innerHTML) + numToAdd;
rows[foundin].cells[1].innerHTML = num;
}
else{
var Row = secondTable.insertRow();
for (var f = 0; f < 2; f += 1) {
Row.insertCell(f);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
}
}
is this what you're looking for?
$(document).ready(function() {
$('.insert').on('click', function() {
var Fruits = ["Apples", "Oranges", "Strawberries"];
var random_Fruit = Fruits[Math.floor(Math.random() * Fruits.length)];
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(random_Fruit);
clone.appendTo('#firstTableBody');
});
$('#firstTableBody').on('click', '.sell', function(e) {
e.preventDefault();
var item = $(this).closest('tr').find('.item').html();
var add = parseInt($(this).closest('tr').find('.number').html());
var inTable2 = [];
$('#secondTable tr').each(function() {
var fruit = $(this).find('.item').html();
inTable2.push(fruit);
});
console.log(inTable2);
if ($.inArray(item, inTable2) > -1) {
console.log('in array');
$('#secondTable tr').each(function() {
var fruitIn2 = $(this).find('.item').html();
if (fruitIn2 == item) {
var sold = parseInt($(this).find('.number').html());
$(this).find('.number').html(sold + add);
}
});
}
else {
console.log('add');
var clone = $('#template').clone(true).attr('id', '');
clone.css('display', '');
clone.closest('tr').find('.item').html(item);
clone.closest('tr').find('.sellTd').remove();
clone.appendTo('#secondTable');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<thead>
<th>Item</th>
<th>Number</th>
<th>
<button class="insert">Insert</button>
</th>
</thead>
<tbody id="firstTableBody">
<tr id="template" class="fruit" style="display:none;">
<td class="item"></td>
<td class="number">100</td>
<td class="sellTd"><button class="sell">Sell</button></td>
</tr>
</tbody>
</table>
<br/><br/>
<table border="1">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTable">
</tbody>
</table>
sorry i kinda used all jquery cause it makes it simpler for me to code in and think xp but it works :D

Javascript cell color according to math

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.

Categories