khemikal khemikal - 1 year ago 57
Javascript Question

Merge each row above parent with parent/children?

I have an HTML table that has a column to the left (parent classes) and columns/rows to the right (children classes). The first column spans several rows while the ones to the right do not. I am attempting to merge each row that is above a parent into the parent below it. Example: Subtotal above Group 1 merged with Group 1 instead of its own row. A little weird to explain so here is my jsfiddle link:

Here is my function:

$(document).ready(function() {
$(".parent").each(function(index, element) {
var subTotal1 = 0;
var subTotal2 = 0;
var subTotal3 = 0;
var numRows = parseInt($(this).attr("rowspan"));
var firstRow = $(this).parent();
var currentRow = firstRow;
for (i = 0; i < numRows; i++) {
subTotal1 += parseInt($(currentRow.children(".child")[0]).text());
subTotal2 += parseInt($(currentRow.children(".child")[1]).text());
subTotal3 += parseInt($(currentRow.children(".child")[2]).text());
currentRow ="tr");
firstRow.before('<tr><td></td><td class="sub0">Sub Total</td><td class="sub1">' + subTotal2 + '</td><td class="sub2">' + subTotal3 + '</td></tr>');

Any help or advice on achieving this would be appreciated.

Answer Source

I've taken your code and simply rearranged it.

I've placed the tr at the end, however, this can easily be moved back to the top.

What you were wanting to do was expand the group's rowspan. Since you already have the numRows variable, I simply added 1 to it and reapplied it to the group.

Edit to make it apply to multiple groups, we have to determine the lastRow of each group. I've done this with the named variable. Now, we can ensure that we append the subtotal to the last row before we increment the row's rowspan value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download