Reputation: 9054
I have a table like blow code:
<table class="somting">
<tr>
<th>Id</th>
<th>Item</th>
<th>Item Cost</th>
</tr>
<tr>
<td>1</td>
<td>Car</td>
<td>200</td>
</tr>
<tr>
<td>2</td>
<td>Book</td>
<td>500</td>
</tr>
<tr>
<td>3</td>
<td>Pen</td>
<td>100</td>
</tr>
</table>
Now my problem is that how can I get the sub total of Item costs column with jquery
I mean how to add 200+500+100
Upvotes: 1
Views: 451
Reputation: 4637
Use this:
<script>
$(document).ready(function() {
var table = $("table.somting");
var tds = table.find("tr td:nth-child(3)");
var sum = 0;
$.each(tds, function(i, me){
var val = parseFloat($(me).text());
sum += val;
});
var append = '<tr><td></td><td></td><td class="price"> '+sum+'</td></tr>';
table.append(append);
});
</script>
Upvotes: 0
Reputation: 7768
var sum =0;
$('table tr:not(:first)').each(function() {
var lasttd= $(this).find(':last-child')
sum+=parseInt(lasttd.text());
});
alert(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="somting">
<tr>
<th>Id</th>
<th>Item</th>
<th>Item Cost</th>
</tr>
<tr>
<td>1</td>
<td>Car</td>
<td>200</td>
</tr>
<tr>
<td>2</td>
<td>Book</td>
<td>500</td>
</tr>
<tr>
<td>3</td>
<td>Pen</td>
<td>100</td>
</tr>
</table>
Upvotes: 0
Reputation: 743
Try this
tot = 0;
$('table.somting tr').each(function(index, elem) {
p = $(this).find(":nth-child(3)").html();
p = parseInt(p);
if (!isNaN(p)) {
tot = tot + p;
}
});
console.log(tot);
Upvotes: 0
Reputation: 2800
<table class="somting">
<tr>
<th>Id</th>
<th>Item</th>
<th>Item Cost</th>
</tr>
<tr>
<td>1</td>
<td>Car</td>
<td>200</td>
</tr>
<tr>
<td>2</td>
<td>Book</td>
<td>500</td>
</tr>
<tr>
<td>3</td>
<td>Pen</td>
<td>100</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var table = $("table.somting");
var tds = table.find("tr td:nth-child(3)");
var sum = 0;
$.each(tds, function(i, me){
var val = parseFloat($(me).text());
sum += val;
});
var append = '<tr><td></td><td></td><td class="price"> '+sum+'</td></tr>';
table.append(append);
});
</script>
Upvotes: 0
Reputation: 82241
You can use :nth-child():
sum=0;
$('.somting td:nth-child(3)').each(function(){
sum += parseInt($(this).text());
})
//log sum
Upvotes: 2
Reputation: 11
You add a class to item code row like
<tr>
<td>1</td>
<td>Car</td>
<td class="price">200</td>
</tr>
and then use
var total = 0;
$(".price").each(function(){
total += parseFloat( $(this).html());
});
see http://jsfiddle.net/8wqppuo6
Upvotes: 0