Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum input fields values when checkbox are checked

Tags:

jquery

i need help please for my project. I have to make 2 functions:

  1. For all lines, once checkbox is checked, i want to get value from input field to calculate sum (it's ok)
  2. For lines checked, while input field value is updated, i want to to recalculate the sum.

Here is my code:

$(document).ready(function(){

  $('.art').change(function(){
   var total = 0;
   $('.art:checked').each(function(){
     var id=$(this).val();
     total+=parseFloat($('#prix'+id).val());
   });
   $('#total').html(total);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<table>
  <tr>
    <td><input type="checkbox" class="art" id="art1" name="article[1]" value="1" /> 1x Stère de bois longueur 50cm</td>
    <td align="right"><input type="text" class="text prix" style="width:60px; text-align:center;" id="prix1" name="prix[1]" value="200.00" />&nbsp;€</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="art" id="art2" name="article[2]" value="2" /> 2x Stère de bois longueur 50cm</td>
    <td align="right"><input type="text" class="text prix" style="width:60px; text-align:center;" id="prix2" name="prix[2]" value="250.00" />&nbsp;€</td>
  </tr>
</table>

<span id="total"></span>

Any help would be appreciated ! Thank you.

like image 959
François Macchi Avatar asked Feb 18 '26 11:02

François Macchi


1 Answers

You need two types of event listener which both call a same function. So I suggest creating a function for recalculate and use it for both types of changes:

function calcTotal() {
  var total = 0;
  $('.art:checked').each(function() {
    var id = $(this).val();
    var val = parseFloat($('#prix' + id).val()) || 0;
    total += val;
  });
  $('#total').html(total.toFixed(2));
}

// When checkbox changes
$('.art').on('change', function() {
  calcTotal();
});

// When price input changes
$('.prix').on('input', function() {
  calcTotal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<table>
  <tr>
    <td><input type="checkbox" class="art" id="art1" name="article[1]" value="1" /> 1x Stère de bois longueur 50cm</td>
    <td align="right"><input type="text" class="text prix" style="width:60px; text-align:center;" id="prix1" name="prix[1]" value="200.00" />&nbsp;€</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="art" id="art2" name="article[2]" value="2" /> 2x Stère de bois longueur 50cm</td>
    <td align="right"><input type="text" class="text prix" style="width:60px; text-align:center;" id="prix2" name="prix[2]" value="250.00" />&nbsp;€</td>
  </tr>
</table>

<span id="total"></span>
like image 138
Ali Sheikhpour Avatar answered Feb 20 '26 01:02

Ali Sheikhpour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!