Skip to content Skip to sidebar Skip to footer

How To Combine Morethan 2 Duplicate Rows And Sum The Value In Html Table Using Jquery

I'm stuct with html table. I want to combine morethan 2 duplicate rows and sum the values in the duplicate rows. My table table Example: Name   Amount john         200 joh

Solution 1:

Another approach using jQuery .nextAll() and .filter()

$('.row').each(function() {
  var thisId = $(this).find('.id').text();
  var sumVal = parseFloat($(this).find('.val').text());

  var $rowsToGroup = $(this).nextAll('tr').filter(function() {
    return $(this).find('.id').text() === thisId;
  });

  $rowsToGroup.each(function() {
    sumVal += parseFloat($(this).find('.val').text());
    $(this).remove();
  });

  $(this).find('.val').text(sumVal);
});

Solution 2:

Try this:

var json = {};
    //Sum up everything and erase
    $.each($('.row'), function (index, curRow) {                                    
        var curName=$(curRow).find('.id').text();   
        var curQty=$(curRow).find('.val').text();
        if (json[curName] != null){
            json[curName] += parseInt(curQty);
        } else {
            json[curName] = parseInt(curQty);               
        }
        $(this).remove();
    });
    //Rebuild table
    jQuery.each(json, function(name, val) {
        $('table').append('<tr class="row"><td class="id">'+name+'</td><td class="val">'+val+'</td><td class="date">date</td></tr>');
    });

Post a Comment for "How To Combine Morethan 2 Duplicate Rows And Sum The Value In Html Table Using Jquery"