Sum of values from different divs with the same class
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/
To build on what Rionmonster's did, this works for me:
HTML:
<div class="totalprice">6.7</div>
<div class="totalprice">8.9</div>
<div class="totalprice">4.5</div>
JavaScript:
var sum = 0;
$('.totalprice').each(function()
{
sum += parseFloat($(this).text());
});
alert(sum);
Output:
21.1
I find that in getting the value out of a <div>
you have to use the .text()
selector. Here is the fiddle to see it work:
http://jsfiddle.net/davecoulter/7D7nR/
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.
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
if($(element).val()!="")
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
alert($('.abcd').sum());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='abcd' value='1'>
<input type='text' class='abcd' value='5'>
More JQUERY Codes