Reputation: 1557
I have this script
$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});
What it does is get the column that has the class price then supposedly adds it all up.
However, all I get from this code is NaN. I don't get what's wrong with the code.
Please note the script if(price == ''). I've done this because initially there are no contents in the table.
Edit: Here the html
<table>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr>
<td>pen</td>
<td class="price>6</td>
<td>paper</td>
<td class="price>8</td>
</tr>
</table>
Upvotes: 1
Views: 1297
Reputation: 8280
Try using the You'll want to declare the .text()
method instead of .html()
method, it should hopefully help get rid of the NaN errors.total
outside the scope of each iteration so it doesn't get reset each time. Try giving this a go, I've simplified it slightly to also include a check against the number price
:
var total = 0;
$('table#preview td.price').each(function()
{
var price = parseInt($(this).text());
if (!isNaN(price))
{
total += price;
}
});
alert('The total is: ' + total);
Here's a jsFiddle. N.B. .html()
should also work.
Upvotes: 7