-4

I have 3 checkboxes with different id's:

<input type="checkbox" value="3.99" id="one" checked>
<input type="checkbox" value="5.99" id="two">
<input type="checkbox" value="7.99" id="three">

And also a field with total value of checked boxes:

<div id="total">3.99</div>

I need simplest jquery solution to calculate values on the go. For example if I check id's "one" and "two" the div "total" should look like this:

<div id="total">9.98</div>

3 Answers3

2

you can write something in this way:

$('input:checkbox').on('change', function () {

 if(this.checked)
    $('#total').text(parseFloat($('#total').text()) + parseFloat($(this).val()))

}).trigger("change")

FIDDLE EXAMPLE

REVISED:

This one is more perfect and effective.

HTML:

<input type="checkbox" class="check" value="3.99" id="one" checked>
<input type="checkbox" class="check" value="5.99" id="two">
<input type="checkbox" class="check" value="7.99" id="three">
<div id="total">0</div>

JQUERY:

$('input:checkbox').on('change', function () {
    var sum = 0;


    $('.check').each(function () {

        if (this.checked) sum = sum + parseFloat($(this).val());

    });

    $('#total').text(sum)

}).trigger("change")

REVISED FIDDLE

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

Use:

var $cbs = $(':checkbox');
$cbs.change(function(){
var total = 0; //$("#more").val();
$cbs.each(function() {
    if ($(this).is(":checked"))
        total += parseFloat($(this).val());
});
alert(total);
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1
$("input[type=checkbox]").change(function(){
    updateTotal();
});

function updateTotal(){
    var total = 0;
    $("input[type=checkbox]:checked").each(function(){
        total += parseFloat($(this).val());
    });
    $("#total").html(total);
}

Demo http://jsfiddle.net/vnwL92b4/

try it

Parfait
  • 1,752
  • 1
  • 11
  • 12