multiple checkbox sum and totals in php-loop

Viewed 67

my problem is to get a dynamic total for each checkbox group coming from a PHP loop
unique array-items comes from mysql database loop

<?php 

$price_list = array(1, 7, 8, 10, 12, 15);

foreach($price_list AS $price){ ?>
    
<div>
    <span>Price-Group <?php echo $price;?></span>
    <form method="post" action="">
      <input type="text" value="20.50" id="price<?php echo $price;?>"><br>
          Option 1<input type="checkbox" value="1.50" data-id="<?php echo $price;?>"><br>
          Option 2<input type="checkbox" value="2.50" data-id="<?php echo $price;?>"><br>
          Option 3<input type="checkbox" value="3.50" data-id="<?php echo $price;?>"><br>
      <input type="text" id="total<?php echo $price;?>" value="20.50">
  </form>
</div>
<hr>

<?php } ?>

and here is my problem jquery-code (i need a dynamic total)

<script>
$('input:checkbox').change(function(){

    var id = $(this).attr('data-id');
    var total = parseFloat($('#price'+id).val());

  $('input:checkbox:checked').each(function(){
      total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
  });

  $('#total'+id).val(total);

});
</script>
1 Answers

OK, I spotted a problem in your Javascript. In the middle you do:

  $('input:checkbox:checked').each(function () {....});

and this function is therefore applied to all checked checkboxes. You only want to apply the function to checked checkboxes in the pricegroup, to which the checkbox that changed belongs. Something like this:

  $('#form' + id + ' input:checkbox:checked').each(function () {....});

Now you don't have a form id, so I had to add that. See: code example.

Note that you don't have to give each checkbox an individual data-id, because from them you can access the form id. For instance, when a checkbox changed:

var id = $(this).parent().attr('id');

would give you the whole form id.

Related