Ad Code

Responsive Advertisement

Row cell merge grouping of html table by jquery and angualar js

This is the common problem for every programmer how can i cell merge in html table.

Let’s take following HTML table as an example:


<table border="1" cellpadding="3" cellspacing="0" id="myTable">
<tbody>
<tr><th>Category</th><th>Product</th><th>Size</th><th>Price</th><th>Shipping</th></tr>
<tr><td>Category-1</td><td>Product-1</td><td>Big</td><td>102</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-1</td><td>Big</td><td>132</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-2</td><td>Big</td><td>130</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-2</td><td>Small</td><td>100</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Big</td><td>130</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Big</td><td>100</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Small</td><td>100</td><td>10</td></tr>
<tr><td>Category-2</td><td>Product-4</td><td>Big</td><td>150</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Big</td><td>150</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Small</td><td>120</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Big</td><td>120</td><td>Free</td></tr>
<tr><td>Category-4</td><td>Product-6</td><td>Big</td><td>120</td><td>10</td></tr>
<tr><td>Category-4</td><td>Product-6</td><td>Small</td><td>120</td><td>10</td></tr>

</tbody></table>

Before using the following method, Make sure the data is sorted. The logic is to check row by row if data is same in next row’s td, remove next row’s td and increase rowspan of current row’s td.


$(function() { 

function groupTable($rows, startIndex, total){
if (total === 0){
return;
}
var i , currentIndex = startIndex, count=1, lst=[];
var tds = $rows.find('td:eq('+ currentIndex +')');
var ctrl = $(tds[0]);
lst.push($rows[0]);
for (i=1;i<=tds.length;i++){
if (ctrl.text() ==  $(tds[i]).text()){
count++;
$(tds[i]).addClass('deleted');
lst.push($rows[i]);
}
else{
if (count>1){
ctrl.attr('rowspan',count);
groupTable($(lst),startIndex+1,total-1)
}
count=1;
lst = [];
ctrl=$(tds[i]);
lst.push($rows[i]);
}
}
}
groupTable($('#myTable tr:has(td)'),0,3);
$('#myTable .deleted').remove();
});


groupTable method has 3 arguments:
$rows: jQuery object of table rows to be grouped
startIndex: index of first column to be grouped
total: total number of columns to be grouped
In above code startIndex =0 and total = 3 it means table is grouped by first, second and third column. After grouping, you need to remove deleted class elements like this:
$(‘#myTable .deleted’).remove();

Post a Comment

0 Comments

Close Menu