Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum all values for table column based on class

Tags:

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> 
like image 228
Khuram Malik Avatar asked Feb 15 '12 12:02

Khuram Malik


People also ask

How do I SUM a specific column in SQL?

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.

How do I SUM the price column from HTML table using Javascript?

You need to format your output: "SubTotal = $" + sumVal. toFixed(2);


2 Answers

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); 
like image 105
Rob Hruska Avatar answered Sep 18 '22 17:09

Rob Hruska


I have a JQuery plugin, Sumtr, that handles this pretty well if you want a summary row.

Here is your example with the plugin.

like image 21
Larsenal Avatar answered Sep 16 '22 17:09

Larsenal