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>
Try using theYou’ll want to declare the.text()method instead of.html()method, it should hopefully help get rid of the NaN errors.totaloutside 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 numberprice:Update
Here’s a jsFiddle. N.B.
.html()should also work.