shrey Pav shrey Pav - 2 months ago 9
HTML Question

How to merge cells with equal values

I have this Table where I need to merge cells with same value for a column Week.
Below is the Table I am getting as an output right now:

Week Project OS TotalTests #cycle of run
1 P1 Windows 0 0
1 P2 Linux,UFO 4799 1


I want the output to be like ( 1 should be placed at the center of a cell) :

Week Project OS TotalTests #cycle of run
1 P1 Windows 0 0
P2 Linux,UFO 4799 1


Here is the code:

function BindTable(startWW, endWW, selPhaseNumber, selctedYear) {
var url = webApiUrl + .....

$('#GraphTable > tbody > tr ').remove();
$.ajax({
url:url,
type: "Get",
dataType: "json",
data: { .... },
crossDomain: true,
success: function (data) {
if (data.length > 0) {


var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].WW + "</td>");

tr.append("<td>" + data[i].Project + "</td>");

tr.append("<td>" + data[i].OS + "</td>");

tr.append("<td>" + data[i].TotalTests + "</td>");

tr.append("<td>" + data[i].CycleRun + "</td>");

$('#GraphTable').append(tr);
}

}
else {
tr = $('<tr/>');
tr.append("<th colspan='10' style='text-align:center'>No Data to display</th>");

$('#GraphTable').append(tr);
}
}
});
}


Any help ?

Answer Source

You can combine cells with the rowspan attribute. The Problem: If you loop through the data from the beginning, you don't know the right value for the rowspan-attribute, because ithas to be placed in the first td-element!

Solution: Loop through it from the end to the beginning:

function success(data) {
  if (data.length > 0) {
    var oldValue = data[data.length-1].WW,
        c=1;
    for (var i = data.length-1; i >= 0; i--) {
      let $tr = $('<tr/>');
      if(i==0 || oldValue != data[i-1].WW) {
        $tr.append("<td rowspan=\""+c+"\">" + data[i].WW + "</td>");
        c = 1;
        if(i>0) oldValue = data[i-1].WW;
      } else {
        c++;
      }
      $tr.append("<td>" + data[i].Project + "</td>");
      $tr.append("<td>" + data[i].OS + "</td>");
      $tr.append("<td>" + data[i].TotalTests + "</td>");
      $tr.append("<td>" + data[i].CycleRun + "</td>");
      $('#GraphTable').prepend($tr);
    }
  } else {
    let $tr = $('<tr/>');
    $tr.append("<th colspan='5' style='text-align:center'>No Data to display</th>");
    $('#GraphTable').append($tr);
  }
}

working fiddle

EDIT: working fiddle with head-line

changed the loop order and naming convention.