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 €</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 €</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?
var tot = tot + checkValues[i];- thetoton right hand side is not initialized . hence the result. Put the declaration outside the loopvar tot=0;checkValuescontains an array of numbers? Have you read the documentation for.attr()? It always returns a string (orundefined).for(var i=0;i<checkValues.length;i++) { var tot = tot + checkValues[i]; alert(tot); }to this:var i,tot=0; for(i=0;i<checkValues.length;i++) { tot = tot + +checkValues[i]; alert(tot); }. Javascript doesn't have block scope - so it's less confusing if you write it outside of theforblock. Also, you should initializetotto zero because in the first iterationtot's value isundefined