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>
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.
You need to format your output: "SubTotal = $" + sumVal. toFixed(2);
You want to use text()
instead of this.value
(since <td>
s don't have a "value"):
var sum = 0; // iterate through each td based on class and add the values $(".price").each(function() { var value = $(this).text(); // add only if the value is number if(!isNaN(value) && value.length != 0) { sum += parseFloat(value); } });
Also, you're looping over your .price
elements (calling calculateSum
) multiple times. You can replace
$(document).ready(function(){ $('.price').each(function() { calculateSum(); }); });
with
$(calculateSum);
I have a JQuery plugin, Sumtr, that handles this pretty well if you want a summary row.
Here is your example with the plugin.
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