merging selected cells of a dynamically created table using jquery - javascript

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" />

Related

Get html table row and cell index with javascript function

I neet to return row and cell index according to user click in table.
My function:
function updatePrice()
{
var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];
for(var i = 0; i < table.rows.length; i++){
table.rows[i].onclick = function valorLinha() {
rIndex = this.rowIndex;
/*console.log here works fine*/
};
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
cellIndex = this.cellIndex;
};
/*I NEED values of rIndex and cellIndex here*/
console.log(rIndex);
console.log(cellIndex);
}
}
I'm getting undefined when console.log runs.
How can I solve this?
var table = document.getElementsByTagName('table')[0];
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++){
table.rows[i].cells[j].onclick = function(){
console.log("Row = "+i+" Cell = "+j)
}
}
}
rIndex is the same as i variable in the loop
and cellIndex is a collection you should loop it
function updatePrice()
{
var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];
for(var i = 0; i < table.rows.length; i++){
var rowi = table.rows[i];
// rIndex = rowi.rowIndex = i;
rIndex = i;
console.log(rIndex);
// cellIndex are multiple, you should loop
for (var j = 0; j < rowi.cells.length; j++){
var cellj = rowi.cells[j];
cellIndex = cellj.cellIndex;console.log(cellIndex);
}
}
}```
document.querySelectorAll('#table td')
.forEach(e => e.addEventListener("click", function() {
// Here, `this` refers to the element the event was hooked on
console.log("clicked cell at: " + this.cellIndex + ", " + this.parentNode.rowIndex);
}));
td{
cursor:pointer;
}
<table id="table">
<tbody>
<tr>
<td>00</td>
<td>10</td>
</tr>
<tr>
<td>01</td>
<td>11</td>
</tr>
<tr>
<td>02</td>
<td>12</td>
</tr>
</tbody>
</table>

Unselect highlighted row

I have this table, and I can't seem to find out how to unselect marked field, if it's clicked again? So a double-click on id 2 would select->unselect.
function highlight_row() {
var table = document.getElementById('testresultsTable');
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function () {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.style.backgroundColor = "yellow";
rowSelected.className += " selected";
}
}
} //end of function
window.onload = highlight_row;
<table id="testresultsTable">
<thead>
<th>ID</th>
<th>Tests</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TESTRUN1</td>
</tr>
<tr>
<td>2</td>
<td>TESTRUN2</td>
</tr>
<tr>
<td>3</td>
<td>TESTRUN3</td>
</tr>
</tbody>
</table>
I thought about making some kind of count on the rowID, so if it's clicked more than once after each other, then it would toggle between select/unselect?
You can solve it by doing something similar to this, this will first check the selected row for the selected class and remove it if it is found, otherwise, it'll add it to the row you clicked. After that is done, this function will loop through all other rows, check if they aren't the clicked row and remove the selected state accordingly.
So now once you click, your code will look for selected on the row you clicked, if it is found, it'll remove that class to reset the styling, if it isn't found, it'll add the selected class. After this, the code will check all rows to see if they're not the selected row and style them accordingly.
function highlight_row() {
var table = document.getElementById('testresultsTable');
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function() {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row++) {
if(row !== rowId) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
if (rowSelected.classList.contains('selected')) {
rowSelected.style.backgroundColor = "";
rowSelected.classList.remove('selected');
} else {
rowSelected.style.backgroundColor = "yellow";
rowSelected.classList.add("selected");
}
}
}
} //end of function
window.onload = highlight_row;
<table id="testresultsTable">
<thead>
<th>ID</th>
<th>Tests</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TESTRUN1</td>
</tr>
<tr>
<td>2</td>
<td>TESTRUN2</td>
</tr>
<tr>
<td>3</td>
<td>TESTRUN3</td>
</tr>
</tbody>
</table>
Hope this helps!
function highlight_row() {
var table = document.getElementById('testresultsTable');
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function () {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row++) {
if(row!==rowId){
rowsNotSelected[row].style.backgroundColor = "white";
rowsNotSelected[row].classList.remove('selected');
}
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
if(rowSelected.classList.contains("selected")) {
rowSelected.style.backgroundColor = "";
rowSelected.classList.remove("selected");
}
else{
rowSelected.style.backgroundColor = "yellow";
rowSelected.classList.add("selected");
}
}
}
} //end of function
window.onload = highlight_row;
<table id="testresultsTable">
<thead>
<th>ID</th>
<th>Tests</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TESTRUN1</td>
</tr>
<tr>
<td>2</td>
<td>TESTRUN2</td>
</tr>
<tr>
<td>3</td>
<td>TESTRUN3</td>
</tr>
</tbody>
</table>
I'd do it like this
var selected;
(function () {
var rows = document.querySelectorAll('#testresultsTable > tbody > tr');
rows.forEach(tr => tr.addEventListener('click', () => {
if(selected === tr){
selected.classList.remove('selected');
selected = undefined;
}
else {
if(selected) selected.classList.remove('selected');
selected = tr;
tr.classList.add('selected');
}
}));
})();
tbody > tr {
cursor: pointer;
user-select: none;
}
tr.selected {
background-color: yellow;
}
<table id="testresultsTable">
<thead><th>ID</th><th>Tests</th></thead>
<tbody>
<tr><td>1</td><td>TESTRUN1</td></tr>
<tr><td>2</td><td>TESTRUN2</td></tr>
<tr><td>3</td><td>TESTRUN3</td></tr>
</tbody>
</table>

Adding table rows and column dynamically with jQuery

I'm trying to add rows and columns to a table using user input values to determine the number of rows and columns dynamically using jQuery. Below is my code which actually adds rows and columns but not according to the user's inputs
function makeGrid() {
let numOfRow = 0; let numOfCol = 0;
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
for (var i = 1; i <= numOfRow; i++) {
let row = $('.grid-canvas').append('<tr>');
for (col = 1; col <= numOfCol; col++) {
$('tr').append('<td></td>');
}
}
});
}
makeGrid();
Assuming a user inputs numOfRow = 2 and numOfCol = 2, I should have a table like this
<tbody class="grid-canvas">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
Problem is my code seems to be adding extra but I haven't been able to figure it out. This is the result of my code
<tbody class="grid-canvas">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
How do I fix my code?
try changing your code from:
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
for (var i = 1; i <= numOfRow; i++) {
let row = $('.grid-canvas').append('<tr>');
for (col = 1; col <= numOfCol; col++) {
$('tr').append('<td></td>');
}
}
});
into this
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
var body = $('.grid-canvas');
for (var i = 1; i <= numOfRow; i++) {
let row = $('<tr></tr>');
for (col = 1; col <= numOfCol; col++) {
row.append('<td></td>');
}
body.append(row);
}
});
what i have done in the above code is created a separate object for the table's body and then once my rows are created with the columns, I append them back to the table object.
Pure javascript code is here
function f(x, y) {
var rows = x,
rowButtonNumber = y;
var table = document.getElementById("myTable");
table.innerHTML = "";
for (var i = 0; i < rows; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
for (var j = 0; j < rowButtonNumber; j++) {
var td = document.createElement("td");
var btn = document.createElement("button");
btn.innerHTML = "btn " + (i + 1);
btn.id = "btn-" + i;
btn.onclick = function() {
alert(this.innerHTML);
};
td.appendChild(btn);
tr.appendChild(td);
}
}
}
function go() {
var row = document.getElementById("row").value;
var col = document.getElementById("col").value;
f(row, col);
}
<html>
<head>
<style>
td {
width: 200px;
height: 200px;
}
button {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
Rows
<input id="row" type="number" placeholder="Rows" />
<br> Columns
<input id="col" type="number" placeholder="Columns" />
<button onclick="go()">Go</button>
<table id="myTable" cellspacing="50">
</table>
</body>
It does not seem you are using the row variable. I would suggest appending newly created td to row instead of $('tr').

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

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