Sum column totals depending on text of another column using jQuery - javascript

I have this code that I use to calculate totals in specific columns based on the text in a different column. It works just fine, but I'm learning, so I would like to know if there is way to consolidate this code. As you can see I run a "each()" twice, once for each column. The first each check for "A" in the first column, then goes to the second column and adds the rows that meet the criteria. Similar on the second column, just that it looks for "B" and add columns 3. Is there a way to run the each function only once and check both column at the same time?
JS:
//Second Column
var total = 0;
$("#theTable tr:contains('A') td:nth-of-type(2)").each(function () {
var pending = parseInt($(this).text());
total += pending;
});
$("#theTable tfoot tr:last-of-type td:nth-of-type(2)").text(total);
//Third Column
var total2 = 0;
$("#theTable tr:contains('B') td:nth-of-type(3)").each(function () {
var pending2 = parseInt($(this).text());
total2 += pending2;
});
$("#theTable tfoot tr:last-of-type td:nth-of-type(3)").text(total2);
HTML:
<table id="theTable">
<thead>
<tr>
<th>MONTH</th>
<th>PENDING</th>
<th>DENIED</th>
</tr>
</thead>
<tbody></tbody>
<tr>
<td>A</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>B</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>B</td>
<td>4</td>
<td>2</td>
</tr>
<tfoot>
<tr>
<td>TOTALS:</td>
<td></td>
<td></td>
</tr>
</tfoot>
This may look simple for some of you, but again, I'm just learning some JS now.
Thanks!

You could try something like this:
var total = {A:{row:1,t:0},B:{row:2,t:0}};
$('#theTable tr').each(function() {
$row = $(this);
$.each(total, function(key, col) {
rowFil = $row.filter(':contains("' + key + '")');
col.t += (rowFil) ? +rowFil.find('td:eq(' + col.row + ')').text() : 0;
});
});
$("#theTable tfoot tr:last td:eq(1)").text(total.A.t);
$("#theTable tfoot tr:last td:eq(2)").text(total.B.t);

someThing of this sort might Help ...
var trs = $('#'+tblID).find('tr');
var total1 = 0;
var total2 = 0;
$.each(trs, function(k, v) {
if ($(v).text == "A"){
total1 += parseInt($(v).parent('tr').find('td:eq(2)').text());
}
if ($(v).text == "B"){
total2 += parseInt($(v).parent('tr').find('td:eq(3)').text())
}
});

Here is another approach - I've summed up all statistics for all possible values:
var totals = [];
$('#theTable tbody tr').each(function(e) {
var tds= $(this).find('td');
var index = $(tds[0]).text();
var pending = parseInt($(tds[1]).text(), 10);
var denied = parseInt($(tds[2]).text(), 10);
if (totals[index] == undefined)
totals[index] = { Pending: 0, Denied: 0 };
totals[index].Pending += pending;
totals[index].Denied += denied;
});
for (var key in totals)
$('#theTable tfoot').append('<tr><td>'+key+'</td><td>'+
totals[key].Pending+'</td><td>'+totals[key].Denied+'</td></tr>');
I've also updated markup a little, here is jsfiddle. The code may be not so pretty, but doing more stuff and can be refactored.

Creating a second table with the sums makes it easier to analyse the data.
SOLUTION
JS
//make a list of unique months
var months = [];
$('#theTable tr td:nth-of-type(1)').each(function(){
var month = $(this).text();
if(months.indexOf(month) < 0) months.push(month);
});
console.log('months', months);
//make a data structure with sums
var data = {};
var tr = $('#theTable tr');
$.each(months, function(){
var month = this;
data[month] = {
pending: 0,
denied: 0
};
tr.each(function(){
var ch = $(this).children();
var m = $(ch[0]).text();
var pending = $(ch[1]).text();
var denied = $(ch[2]).text();
if(m == month) {
data[month].pending += parseInt(pending);
data[month].denied += parseInt(denied);
}
});
});
console.log('data', data);
//make a table with the data
var table = $('<table>');
table.append($('<tr>'+
'<th>MONTH</th>'+
'<th>PENDING</th>'+
'<th>DENIED</th>'+
'</tr>'));
$.each(data, function(month){
table.append($('<tr>'+
'<td>'+month+'</td>'+
'<td>'+data[month].pending+'</td>'+
'<td>'+data[month].denied+'</td>'+
'</tr>'));
});
$('body').append(table);

Related

get the sum of 2nd column in html table

input : <table> <tr> <td>100</td> </tr> <tr> <td>200</td> </tr> </table> from the input it should return me the sum=300 instead I'm getting the output as 100200
function Save_Name()
{
var Invoice = $("#text_invoice").val();
var Name = $("#text_name").val();
var Date = $("#text_date").val();
var Amount = 0;
var n = $("table").find("tr").length;
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#table1").find("tr").eq(i).find("td").eq(2).text();
Amount += parseFloat(Amt);
}
}
}
eq starts with 0 index.The output 100200 is because it is concatenating the string instead of adding the values.Also use parseInt to convert the number from string to integer.
function Save_Name() {
var Amount = 0;
// will get all tr
var n = $("#table1 tr");
n.each(function(i, v) {
// table have only one td per tr so eq(0) will give first td
// trim is used to remove any white space
Amount += parseInt($(v).eq(0).text().trim(), 10)
})
console.log(Amount)
}
Save_Name()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
Here's another way to do the same thing. Basically, I use map to create a map of integer values, then I use "get" to convert them into an array, and finally I use reduce to calculate the sum of the values in the array.
P.S.: To calculate the second column, all you need to do is to use nth-child(2) instead of nth-child(1).
$(function(){
var sum = $('#table1 tr td:nth-child(1)').map(function() {
return parseInt($(this).html(), 10)
}).get().reduce(function(a, v){
return a + v;
}, 0);
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
I have alert the value of sum Amount and it is equal to 300 .
You were doing some mistake as eq(2) instead of eq(0)
But Here's the working snippet:
function Save_Name()
{
var Amount = 0;
var n = $('#test tr').length;
// alert(n);
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#test").find("tr").eq(i).find("td").eq(0).text();
Amount += parseFloat(Amt);
}
alert(Amount);
}
}
Save_Name();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='test'>
<tr> <td>100 </td></tr>
<tr> <td>200 </td></tr>
</table>

jQuery/Javascript compare two tables against each other

I need to compare two HTML tables' rows assuming that data in first cell can be duplicated but data in second cell is always unique. I need to find whether first cell AND second cell in table1 is the same as data in first cell AND second cell in table2 for instance:
Table1:
<Table>
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</Table>
Second table:
<table>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
The result of this should be:
123 321 - good, do nothing
545 345 - good, do nothing
545 3122 - wrong its not in table1 <-
Here's what I've got so far...
$('#runCheck').click(function(){
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
$(secondTable).each(function(index){
var $row = $(this);
var secTableCellZero = $row.find('td')[0].innerHTML;
var secTableCellOne = $row.find('td')[1].innerHTML;
$(firstTable).each(function(indexT){
if ($(this).find('td')[0].innerHTML === secTableCellZero){
if ($(this).find('td')[1].innerHTML !== secTableCellOne){
$('#thirdDiv').append("first: " + secTableCellZero + " second: " + secTableCellOne+"<br>");
}
}
});
});
});
Where am I going it wrong?
Just to clarify once again:
2nd table says :
row1 - john|likesCookies
row2 - peter|likesOranges
1st table says :
row1 - john|likesNothing
row2 - john|likesCookies
row3 - steward|likesToTalk
row4 - peter|likesApples
now it should say :
john - value okay
peter - value fail.
a lot alike =VLOOKUP in excel
Check this working fiddle : here
I've created two arrays which store values in each row of tables 1 and 2 as strings. Then I just compare these two arrays and see if each value in array1 has a match in array 2 using a flag variable.
Snippet :
$(document).ready(function() {
var table_one = [];
var table_two = [];
$("#one tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
}
temp_string = temp_string + $(this).text();
count++;
});
table_one.push(temp_string);
});
$("#two tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
temp_string = temp_string + $(this).text();
} else {
temp_string = temp_string + $(this).text();
}
count++;
});
table_two.push(temp_string);
});
var message = "";
for (i = 0; i < table_two.length; i++) {
var flag = 0;
var temp = 0;
table_two_entry = table_two[i].split("/");
table_two_cell_one = table_two_entry[0];
table_two_cell_two = table_two_entry[1];
for (j = 0; j < table_one.length; j++) {
table_one_entry = table_one[j].split("/");
table_one_cell_one = table_one_entry[0];
table_one_cell_two = table_one_entry[1];
console.log("1)" + table_one_cell_one + ":" + table_one_cell_two);
if (table_two_cell_one == table_one_cell_one) {
flag++;
if (table_one_cell_two == table_two_cell_two) {
flag++;
break;
} else {
temp = table_one_cell_two;
}
} else {}
}
if (flag == 2) {
message += table_two_cell_one + " " + table_two_cell_two + " found in first table<br>";
} else if (flag == 1) {
message += table_two_cell_one + " bad - first table has " + temp + "<br>";
} else if (flag == 0) {
message += table_two_cell_one + " not found in first table<br>";
}
}
$('#message').html(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="one">
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</table>
<hr>
<table id="two">
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
<hr>
<div id="message">
</div>
</div>
If I understand your requirements, it would be easier to read the first table and store the couples as strings: 123/321, 545/345, etc...
Than you can read the second table and remove from the first list all the rows found in both.
What remains in the list are couples that do not match.
From purely an efficiency standpoint if you loop through the first table just once and create an object using the first cell value as keys and an array of values for second cells, you won't have to loop through that table numerous times
this then makes the lookup simpler also
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
var firstTableData = {}
firstTable.each(function() {
var $tds = $(this).find('td'),
firstCellData = $tds.eq(0).html().trim(),
secondCellData == $tds.eq(1).html().trim();
if (!firstTableData[firstCellData]) {
firstTableData[firstCellData] = []
}
firstTableData[firstCellData].push(secondCellData)
})
$(secondTable).each(function(index) {
var $tds = $(this).find('td');
var secTableCellZero = $tds.eq(0).html().trim();
var secTableCellOne = $tds.eq(1).html().trim();
if (!firstTableData.hasOwnProperty(secTableCellZero)) {
console.log('No match for first cell')
} else if (!firstTableData[secTableCellZero].indexOf(secTableCellOne) == -1) {
console.log('No match for second cell')
}
});
I'm not sure what objective is when matches aren't found

Getting coordinates of table cells and comparing with different tables via Javascript

It's really easy to access to coordinates of table cells with this and this example ways. But when I'm trying to get cells and compare with another table's cell which is avaible on page, a problem occurs. Because I don't know how to compare them in same time. After many hours I tried to do this, unfortunately, still there is no luck.
In following classic tables list below, shows 2 different tables with different id numbers:
<table id="a1">
<tbody>
<tr>
<td>RED</td>
<td>GREEN</td>
<td>BLUE</td>
</tr>
<tr>
<td>YELLOW</td>
<td>PINK</td>
<td>samespothere</td>
</tr>
</tbody>
</table>
<hr>
<table id="a2">
<tbody>
<tr>
<td>BLACK</td>
<td>BROWN</td>
<td>WHITE</td>
</tr>
<tr>
<td>CYAN</td>
<td>GRAY</td>
<td>samespothereANDsomeextra</td>
</tr>
</tbody>
</table>
And also, I'm using modified version of this JS example to get location of cells. This modified version I did is not able to make compare operation. I've just edited for make it easier.
var cells = document.getElementsByTagName("td"); //For all table cells on page.
var i;
for(i = 0; i < cells.length; i++)
{
cells[i].onclick = vera;
}
function vera()
{
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
var centra = cellIndex +","+ rowIndex; //This gives the coordinate of cell which you clicked on.
alert(centra);
}
Here is my question: I need to make a compare operation when I click on samespothere(Example text I wrote) table cell. Compare operation should be able with the same location of other table. Lets think like this: If second table cell(same location, different table) includes some of clicked cell's text(from first table), alert must show up and say "This clicked text in table id=1 cell:2row:2, matched in table id=2 cell:2row:2".
And here is the online code: http://jsfiddle.net/LujydnaL/
I think this is what you want:
function vera()
{
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
var centra = cellIndex +","+ rowIndex; //This gives the coordinate of cell which you clicked on.
alert(centra);
// new code here
table2 = document.getElementById('a2');
rowInTable2 = table2.getElementsByTagName('tr')[rowIndex-1];
cellInTable2 = rowInTable2.getElementsByTagName('td')[cellIndex-1];
console.log(cellInTable2);
// do something with cellInTable2 now
}
window.onload = function () {
document.getElementsByTagName('table')[0].addEventListener('click', function(element) {
var rowIndex = element.target.parentElement.rowIndex;
var cellIndex = element.target.cellIndex;
var compare = document.getElementsByTagName('table')[1].rows[rowIndex].cells[cellIndex];
var myNodelist = document.querySelectorAll("td");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "white";
}
compare.style.backgroundColor = "grey";
document.getElementById('alert1').innerHTML = ('CLICK => Row index = ' + rowIndex + ', Column index = ' + cellIndex);
document.getElementById('alert2').innerHTML = ('COMPARE = ' + compare.innerHTML)
}, false);
}
tr, th, td {
padding: 0.2rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td>a11</td>
<td>a12</td>
<td>a13</td>
</tr>
<tr>
<td>a21</td>
<td>a22</td>
<td>a23</td>
</tr>
</tbody>
</table>
<p id="alert1"></p>
<hr>
<table>
<tbody>
<tr>
<td>b11</td>
<td>b12</td>
<td>b13</td>
</tr>
<tr>
<td>b21</td>
<td>b22</td>
<td>b23</td>
</tr>
</tbody>
</table>
<p id="alert2"></p>

jquery .each loop odd behaviour

Hi I have the following code
html
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</table>
script
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
var first;
var second;
$('#tbPermission tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
alert(JSON.stringify(trArray));
Demo Here
My question why first and second in undefined in first alert, and why it is
[{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"}]
my desired output is
[{"UserID":"1","UserName":"Test1"},{"UserID":"2","UserName":"Test2"},{"UserID":"3","UserName":"Test3"}]
The scope of your reruiredObj object is incorrect which is why you get the same object three times. Try this instead:
var trArray = [];
var tdArray = [];
var first;
var second;
$('#tbPermission tr:gt(0)').each(function () {
var reruiredObj = {
"UserID": null,
"UserName": null
};
first = $(this).find('td').eq(0).html();
second = $(this).find('td').eq(1).html();
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
console.log(JSON.stringify(trArray));
jsFiddle example
And the undefined values come from iterating over the first row which you don't want, and can ignore with tr:gt(0)
The first alert gives undefined because the first row of the table does not contain any td element.
To exclude the first row from the loop:
$('#tbPermission tr').each(function (i) {
if (i != 0) {
// execute ..
}
});
As for the array, try this in each loop:
var reruiredObj = { "UserID": first , "UserName":second };
Check the DEMO
Below works fine for me.
Since your first tr doesnt have td it gives undefined error. Try below one
<table id="tbPermission">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</tbody>
</table>
<script>
$(function () {
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
jsonObj = [];
var first;
var second;
$('#tbPermission tbody tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
item = {}
item ["UserID"] = first;
item ["UserName"] = second;
jsonObj.push(item);
});
console.log(jsonObj);
});
</script>
alert jsonObj. This gives the required result.

Iterate over table cells, re-using rowspan values

I have a simple HTML table, which uses rowspans in some random columns. An example might look like
A | B |
---|---| C
D | |
---| E |---
F | | G
I'd like to iterate over the rows such that I see rows as A,B,C, D,E,C, then F,E,G.
I think I can probably cobble together something very convoluted using cell.index() to check for "missed" columns in later rows, but I'd like something a little more elegant...
without jquery:
function tableToMatrix(table) {
var M = [];
for (var i = 0; i < table.rows.length; i++) {
var tr = table.rows[i];
M[i] = [];
for (var j = 0, k = 0; j < M[0].length || k < tr.cells.length;) {
var c = (M[i-1]||[])[j];
// first check if there's a continuing cell above with rowSpan
if (c && c.parentNode.rowIndex + c.rowSpan > i) {
M[i].push(...Array.from({length: c.colSpan}, () => c))
j += c.colSpan;
} else if (tr.cells[k]) {
var td = tr.cells[k++];
M[i].push(...Array.from({length: td.colSpan}, () => td));
j += td.colSpan;
}
}
}
return M;
}
var M = tableToMatrix(document.querySelector('table'));
console.table(M.map(r => r.map(c => c.innerText)));
var pre = document.createElement('pre');
pre.innerText = M.map(row => row.map(c => c.innerText).join('\t')).join('\n');
document.body.append(pre);
td {
border: 1px solid rgba(0,0,0,.3);
}
<table>
<tr>
<td colspan=2>A</td>
<td rowspan=2>B</td>
</tr>
<tr>
<td>C</td>
<td rowspan=3>D</td>
</tr>
<tr>
<td rowspan=2>E</td>
<td rowspan=4>F</td>
</tr>
<tr></tr>
<tr>
<td rowspan=2 colspan=2>G</td>
</tr>
<tr></tr>
<tr>
<td rowspan=3 colspan=3>H</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td colspan=3>I</td>
</tr>
</table>
Try this:
<table id="tbl">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2" rowspan="2">A</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
Script:
var finalResult = '';
var totalTds = $('#tbl TR')[0].length;
var trArray = [];
var trArrayValue = [];
var trIndex = 1;
$('#tbl TR').each(function(){
var currentTr = $(this);
var tdIndex = 1;
trArray[trIndex] = [];
trArrayValue[trIndex] = [];
var tdActuallyTraversed = 0;
var colspanCount = 1;
$('#tbl TR').first().children().each(function(){
if(trIndex > 1 && trArray[trIndex - 1][tdIndex] > 1)
{
trArray[trIndex][tdIndex] = trArray[trIndex - 1][tdIndex] - 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex - 1][tdIndex];
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
else
{
if(colspanCount <= 1)
{
colspanCount = currentTr.children().eq(tdActuallyTraversed).attr('colspan') != undefined ? currentTr.children().eq(tdActuallyTraversed).attr('colspan') : 1;
}
if(colspanCount > 1 && tdIndex > 1)
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex][tdIndex - 1];
colspanCount--;
}
else
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).html();
tdActuallyTraversed++;
}
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
tdIndex++;
});
trIndex++;
});
alert(finalResult);
Fiddle
i am not sure about the performance, but it works well.
what I understood with your question is: You want to split the merged cell with same value and then iterate the table simply by row.
I've created a JSFiddle that will split the merged cells with the same value. Then you'll have a table that can be iterated simply by rows to get the desired output that you specified.
See it running here http://jsfiddle.net/9PZQj/3/
Here's the complete code:
<table id="tbl" border = "1">
<tr>
<td>A</td>
<td>B</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td>D</td>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
<br>
<div id="test"> </div>
Here's the jquery that is used to manipulate the table's data.
var tempTable = $('#tbl').clone(true);
var tableBody = $(tempTable).children();
$(tableBody).children().each(function(index , item){
var currentRow = item;
$(currentRow).children().each(function(index1, item1){
if($(item1).attr("rowspan"))
{
// copy the cell
var item2 = $(item1).clone(true);
// Remove rowspan
$(item1).removeAttr("rowspan");
$(item2).removeAttr("rowspan");
// last item's index in next row
var indexOfLastElement = $(currentRow).next().last().index();
if(indexOfLastElement <= index1)
{
$(currentRow).next().append(item2)
}
else
{
// intermediate cell insertion at right position
$(item2).insertBefore($(currentRow).next().children().eq(index1))
}
}
});
console.log(currentRow)
});
$('#test').append(tempTable);
You can use this Gist. It supports all the requirements by W3C, even "rowspan=0" (which seems to be only supported by Firefox).

Categories

Resources