Giacomo Cerquone
Giacomo Cerquone

Reputation: 2478

Javascript does not sum numbers

I'm not good using javascript/jquery so this is a dumb question! I coded this

    <li>
        <a href="http://www.mazzodifiori.it/fiori/P15-Ficus.jpg"><img src="http://www.mazzodifiori.it/fiori/P15-Ficus.jpg" width=50 height=50 /></a>
        <br><input name="p1" value="p1" prezzo="5" type="checkbox" />
        <br><label>Pianta &euro;</label><span class="price">5</span>
    </li>

    <li>
        <a href="http://www.mazzodifiori.it/fiori/P15-Ficus.jpg"><img src="http://www.mazzodifiori.it/fiori/P15-Ficus.jpg" width=50 height=50 /></a>
        <br><input name="p2" value="p2" prezzo="3" type="checkbox" />
        <br><label>Pianta &euro;</label><span class="price">3</span>
    </li>

var checkValues = $('input[type=checkbox]:checked').map(function() {
    return $(this).attr('prezzo');
}).get();

for(var i=0;i<checkValues.length;i++) {
    var tot = tot + checkValues[i];
    alert(tot);
}

In this way checkvalues contains array of numbers. So checking that 2 checkbox for example, on the browser appear 2 alert:

undefined5

and

undefined53

like if javascript is concatenating numbers like they would be strings!

how can i solve this?

Upvotes: 0

Views: 3781

Answers (4)

user4593252
user4593252

Reputation: 3506

Javascript is a duck typed (loosely typed) language. If it thinks they're strings, it'll concat them. Try forcing them into the data type you need. If they're integers, use parseInt(varName) + parseInt(varName2).

http://www.w3schools.com/jsref/jsref_parseint.asp

Upvotes: 1

thedude
thedude

Reputation: 355

Try to change:

var tot = tot + checkValues[i];

to this:

var tot = tot + +checkValues[i];

OR

change this:
return $(this).attr('prezzo');

to this:

return +$(this).attr('prezzo');

This will coerce the string to a number

Upvotes: 3

hlscalon
hlscalon

Reputation: 7552

Check this out:

var tot = 0;
for(var i=0;i<checkValues.length;i++) {
    tot = tot + parseInt(checkValues[i]);
    alert(tot);
}

Upvotes: 2

Isaac
Isaac

Reputation: 344

You keep reinitializing tot (which isn't strictly speaking a problem in JS, but it's bad form), plus you're initializing it to undefined initially, since you're defining it as itself. Initialize it to 0 before the loop.

Upvotes: 1

Related Questions