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?
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/
$(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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With