Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of values from different divs with the same class

Tags:

jquery

I am loading dynamically divs that have a .totalprice class. At the end, I would like to sum of the values from all of the .totalprice.

like image 573
bobek Avatar asked Aug 30 '11 20:08

bobek


2 Answers

For <div> Elements:

var sum = 0; $('.totalprice').each(function(){     sum += parseFloat($(this).text());  // Or this.innerHTML, this.innerText }); 

You can see a working example of this here

For <input> Elements (inputs, checkboxes, etc.):

var sum = 0; $('.totalprice').each(function(){     sum += parseFloat(this.value); }); 

Alternatively, if you are looking for an integer, you can use the parseInt() function.

You can see a working example of this here.

like image 175
Rion Williams Avatar answered Sep 21 '22 08:09

Rion Williams


Unless you're absolutely certain about the value of your content, you will not be able to use parseFloat out of the box.

You need to be sure to handle:

  • Excessive Whitespace
  • Leading $
  • Blanks
  • Unexpected Strings

Take a look:

<div class="totalprice">  $1.25 </div> <div class="totalprice">0.25     </div> <div class="totalprice">$3.00 </div> <div class="totalprice">  2.50</div> <div class="totalprice">$0.01</div> <div class="totalprice">  </div> 

The following will handle all cases:

var sum = 0;  $(".totalprice").each(function() {     var val = $.trim( $(this).text() );      if ( val ) {         val = parseFloat( val.replace( /^\$/, "" ) );          sum += !isNaN( val ) ? val : 0;     } });  console.log( sum ); 

See also: http://jsfiddle.net/rwaldron/hfA5V/

like image 31
Rick Avatar answered Sep 18 '22 08:09

Rick