i need help please for my project. I have to make 2 functions:
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" /> €</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" /> €</td>
</tr>
</table>
<span id="total"></span>
Any help would be appreciated ! Thank you.
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" /> €</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" /> €</td>
</tr>
</table>
<span id="total"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With