mercredi 7 janvier 2015

jQuery if check-box is checked adding up numbers

i am trying to make a list of options for a user to select to get a price quote, example being:



  • banana check

  • apple check

  • biscuit unchecked

  • jam check


Each option has a value banana $3, apple $2, biscuit $11, jam $1.


Total of example above $4 + $2 + $1.20 = $7.20 (biscuit is not wanted)


I want the total to update as the check boxes are ticked/unticked. The values don't seem to be adding and my code seem to lengthy if i were to add more options.


My Code http://ift.tt/1ByqaNg


As you can probably tell i am very new to JavaScript/jQuery.


Html:



<input type="checkbox" name="checkbox1" id="checkbox1" class="css-checkbox" />
<label for="checkbox1" class="css-label">banana</label><br>

<input type="checkbox" name="checkbox2" id="checkbox2" class="css-checkbox" />
<label for="checkbox2" class="css-label">apple</label><br>


<input type="checkbox" name="checkbox3" id="checkbox3" class="css-checkbox" />
<label for="checkbox3" class="css-label">biscuit</label><br>

<input type="checkbox" name="checkbox4" id="checkbox4" class="css-checkbox" />
<label for="checkbox4" class="css-label">jam </label><br>

<p>Total Cost: $<span id="total"></span></p>


Script:



$total = "";


// Banana $4

$('#checkbox1').click(function(){
if (this.checked) {
$total =+ 4;
$('#total').html( $total );
}
})

// Apple $2

$('#checkbox2').click(function(){
if (this.checked) {
$total =+ 2;
$('#total').html( $total );
}
})

// Biscuit $11

$('#checkbox3').click(function(){
if (this.checked) {
$total =+ 11;
$('#total').html( $total );
}
})

// Jam $1

$('#checkbox4').click(function(){
if (this.checked) {
$total =+ 1;
$('#total').html( $total );
}
})




Aucun commentaire:

Enregistrer un commentaire