Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery math sum method

I need to sum some money value, i have this html

<div class=''>54,44</div>
<div class=''>34,10</div>
<div class=''>44,00</div>
<div class=''>14,50</div>

How can i make an alert with the sum of these div text?? ( the right sum!! ;-) ) Many thanks!

like image 257
Ste Avatar asked Jul 18 '11 10:07

Ste


2 Answers

Add some class like money (or use $("div") selector) and do something like this:

var sum = 0;
$(".money").each(function(){
    sum += parseFloat($(this).text().replace(",", "."));
});

alert(sum);
like image 167
Igor Dymov Avatar answered Sep 23 '22 23:09

Igor Dymov


Firstly, its worthwhile putting a data-attribute on each div with the raw amount, devoid of any locale-specific formatting.

eg/

<div data-amount="55.44">54,44</div>

Then assuming these div's are identifiable you can simply do

var total = 0;
$('some-selector-for-your-divs').each(function(){
   total += parseFloat($(this).data('amount'));
});

Edit: Duh! parseInt on monetery amounts fixed.

like image 45
Jamiec Avatar answered Sep 25 '22 23:09

Jamiec