The explanation is below the code:
The code for HTML is :
Add-ons
I believe that you're simply missing a block for your if
statement in the each
function: you don't want to increment total
unless this.checked
is true. Furthermore, you want to convert all strings to numbers so that you don't get string concatenation from +
- I've used parseInt
. Also, from your description, it seems like you only want to add the value from the option
once, not each time through the loop, so use that to initialize total
:
$cbs.click(function()
{
var total = parseInt($("#more").val());
$cbs.each(function()
{
if (this.checked)
total += parseInt(this.value);
});
$("#usertotal").text(total);
});
But you also want to do this calculation and update when the select
changes, so you should pull this loop out into a separate function and call it using click
:
function calculateTotal()
{
var total = parseInt($("#more").val());
$cbs.each(function()
{
if (this.checked)
total += parseInt(this.value);
});
$("#usertotal").text(total);
}
$("#more").change(calculateTotal);
$cbs.click(calculateTotal);