All Columns
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function MergeCommonRows(table) { var firstColumnBrakes = []; // iterate through the columns instead of passing each column as function parameter: for(var i=1; i<=table.find('th').length; i++){ var previous = null, cellToExtend = null, rowspan = 1; table.find("td:nth-child(" + i + ")").each(function(index, e){ var jthis = $(this), content = jthis.text(); // check if current row "break" exist in the array. If not, then extend rowspan: if (previous == content && content !== "" && $.inArray(index, firstColumnBrakes) === -1) { // hide the row instead of remove(), so the DOM index won't "move" inside loop. jthis.addClass('hidden'); cellToExtend.attr("rowspan", (rowspan = rowspan+1)); }else{ // store row breaks only for the first column: if(i === 1) firstColumnBrakes.push(index); rowspan = 1; previous = content; cellToExtend = jthis; } }); } // now remove hidden td's (or leave them hidden if you wish): $('td.hidden').remove(); } $('.button').click(function(){ MergeCommonRows($('#tbl')); }); |
Escape last column
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function MargeCommonRows(table){ var firstColumnBrakes = []; $.each(table.find('th'),function(i){ var previous = null, cellToExtend = null, rowspan = 1; table.find("td:nth-child("+i+")").each(function(index,e){ var jthis = $(this),content = jthis.text(); if(previous == content && content !== "" && $.inArray(index, firstColumnBrakes) === -1){ jthis.addClass('hidden'); cellToExtend.attr('rowspan',(rowspan = rowspan+1)); }else{ if(i==1) firstColumnBrakes.push(index); rowspan = 1; previous = content; cellToExtend = jthis; } }); }); $('td.hidden').remove(); } |
Leave a reply