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
.
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.
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:
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/
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