0

I have this code from my HTML form.

<?php foreach ($charges as $c): ?>
    <br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>

<div="total"></div>

when I tick a textbox I get the value of the checked checkbox using the following jQuery code.

$('.charge').change(function() {
    var v = $(this).data('cash');
    $('.total').html(v); 
});

// raise the event on checked elements on load:
$('.charge:checked').change();

However, I'm supposed to get the sum of all the values of the checked boxes and display them. In addition, multiply the some values with another number before adding it to the other values from the checked checkboxes.

e.g Assume these are five checkboxes

1800
1200
2000 (if checked, multiply by 4)
3400
2000 (if checked, multiply by 4)

For example, if you check the first 3 checkboxes from top to bottom, the value displayed should be 1800 then 3000 then, since 2000 will be multiplied by 4, get 11000. (that's 1800+1200+8000). The values displayed should also be subtracted automatically when the checkboxes are unchecked.

How do I achieve that?

Richie
  • 1,398
  • 1
  • 19
  • 36
  • 2
    Have you tried anything? – isherwood Mar 11 '15 at 13:27
  • @MikeMcCaughan Nope. Mine has some further manipulations. Multiplying values by some other values. – Richie Mar 11 '15 at 13:44
  • So your question is how to multiply values? Or you can't figure out how to get the selected checkboxes? If the latter, then it's a duplicate of the question provided. If the former... I'm not sure what to say. – Heretic Monkey Mar 11 '15 at 14:05

1 Answers1

4

You need to iterate over the checked items them total them

var $cs = $('.charge').change(function () {
    var v = 0;
    $cs.filter(':checked').each(function () {
        v += $(this).data('cash');
    })
    $('.total').html(v);
});

Demo: Fiddle


another option without the loop is

var $cs = $('.charge').change(function () {
    var total = +$('.total').html().trim() || 0,
        v = $(this).data('cash');
    if (this.checked) {
        total += v
    } else {
        total -= v;
    }
    $('.total').html(total);
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531