Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate sum of each td having similar class

My html table td looks like this

<td class="20">1</td>
<td class="20">2</td>
<td class="20">3</td>
<td class="20">4</td>
<td class="20">5</td>
<td class="20">3</td>
<td class="total"></td>
<td class="30">2</td>
<td class="30">5</td>
<td class="30">6</td>
<td class="total"></td>

I'm trying to count the number of td's available before class total and sum the values and put it in respective total class td.

So i want to get

<td class="20">1</td>
<td class="20">2</td>
<td class="20">3</td>
<td class="20">4</td>
<td class="20">5</td>
<td class="20">3</td>
<td class="total">Total : 18</td>
<td class="30">2</td>
<td class="30">5</td>
<td class="30">6</td>
<td class="total">Total : 13</td>

This is what i have tried.

var sum = 0;
$('.total').each(function(){
var tdTxt = $(this).prev('td').text();
    sum += parseFloat(tdTxt);                       
});

But it doesnt work. how to achieve this?

like image 382
Matarishvan Avatar asked Mar 01 '16 05:03

Matarishvan


2 Answers

Try:

var temp = 0;
$('td').each(function(){

var tdTxt = $(this).text();
     if($(this).hasClass('total')) {
         $(this).text(temp);
         temp = 0;
    } else {
       temp+= parseFloat(tdTxt);    
    } 

});

https://jsfiddle.net/8f4b1tok/

like image 69
madalinivascu Avatar answered Nov 06 '22 18:11

madalinivascu


$(document).ready(function() {

  $('.total').each(function() {
    var prevClass = $(this).prev().attr('class');
    var sum = 0;
    $('.' + prevClass).each(function() {
      sum += Number($(this).text());
    })

    $(this).text('Total :'+sum);
  })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="20">1</td>
    <td class="20">2</td>
    <td class="20">3</td>
    <td class="20">4</td>
    <td class="20">5</td>
    <td class="20">3</td>
    <td class="total">8</td>
    <td class="30">2</td>
    <td class="30">5</td>
    <td class="30">6</td>
    <td class="total"></td>
  </tr>
</table>
like image 4
Pavan Teja Avatar answered Nov 06 '22 18:11

Pavan Teja