I’m facing a little problem with my jQuery / Javascript code.
I have several values on a page, like :
checkbox EXAMPLE EXAMPLE 150
checkbox EXAMPLE EXAMPLE 300
checkbox EXAMPLE EXAMPLE 300
I have this little code, which basically just add the numerical values (150, 300, 300) to an array, and then, sum the array in the “total” variable. (Well, at least this is what I’m trying to do…)
Here’s the code :
$('.pack_check').click(function() {
var cout = [];
total = 0;
$('#services_pack input:checked').each(function() {
cout.push(this.cout);
$.each(cout,function() {
total += parseInt(this);
});
});
});
});
My problem is, that when I click on my first checkbox, it’s ok, total = 150
But, if I click on the second checkbox, total = (150 + 150 + 300) which is a bit annoying…
Anyone ?
Thanks in advance !
The problem is likely that you’ve got a nested loop adding to your total. So for every checked checkbox you first add its
.coutto the array, and then you add every element in the array to the total again. Also you have too many closing});. Try this:Or if you just need the total eliminate the
coutarray:Note that
parseInt()takes a second parameter to specify the radix, so if you want to work in base 10:parseInt(stringToParse,10)– avoids problems if the string starts with a leading0or leading0x, which would otherwise be interpreted as base 8 and base 16 (respectively).Having said that, I recommend the unary plus operator to convert a string to a number: