Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum Javascript variables (strings, actually)

I have three div that contain a number.

<div class="a">10</div> 
<div class="b">20</div>
<div class="c">30</div>

I get the number inside each one with jQuery .html().

var val_1 = $('.a').html(), 
    val_2 = $('.b').html(),
    val_3 = $('.c').html();

How can I sum them?

This do not work as expected:

var total = val_1 + val_2 + val_3;

Since returned 102030, when I expected 60.

like image 461
Hugo M. Avatar asked Dec 04 '22 06:12

Hugo M.


1 Answers

First, since you want only the content of your divs, you'd better use $('.x').text() instead of $('.x').html().

Now what's happening is that you're additioning strings, ie concatening them: '1' + '2' + '3soleil' === '123soleil'.

You want to parse them into numbers, which is done with

Number(val1) + Number(val2) + Number(val3)

If you know they're integers, you can more safely use Number.parseInt(val, 10) (the second variable of that function, called radix, is the mathematic base of your number. It's most likely a decimal number (10), but could be hexadecimal (16), boolean number (2), etc)

like image 191
floribon Avatar answered Dec 09 '22 14:12

floribon