I’m trying to retrieve the sum of all values in a td based on a specific class. The code does not throw up any errors but my sum keeps resulting in “0”.
Do the numerical values have to be specified in a particular way? I saw some other answers here on SO from where have imitated the code, and i dont see any real difference between mine and theirs so im confused as to why mine isnt working.
Here is a tutorial i followed for reference: http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
Here is my javascript
$(document).ready(function(){
$('.price').each(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each td based on class and add the values
$(".price").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$('#result').text(sum);
};
Here is my html
<table border="1">
<tr>
<th>Item</th>
<th>Price</th>
</tr>
<tr>
<td>Banana</td>
<td class ="price">50</td>
</tr>
<tr>
<td>Apple</td>
<td class ="price">100</td>
</tr>
</table>
<div id="result"></div>
You want to use
text()instead ofthis.value(since<td>s don’t have a “value”):Also, you’re looping over your
.priceelements (callingcalculateSum) multiple times. You can replacewith