First of all, please excuse my JS script knowledge. It’s very little and mainly I’m a PHP programmer. I’ve found this great and simple script which calculates the total of the products table rows and also gives the grand total of the whole table. However, it only does the calculation when I change the quantity. Is it possible to make it does the calculation every time I change the price OR the quantity?
Here is the code:
<script type="text/javascript">
$(function () {
$('.subtot, .grdtot').prop('readonly', true);
var $tblrows = $("#tblProducts tbody tr");
$tblrows.each(function (index) {
var $tblrow = $(this);
$tblrow.find('.qty').on('change', function () {
var qty = $tblrow.find("[data-name=qty]").val();
var price = $tblrow.find("[data-name=price]").val();
var subTotal= parseInt(qty, 10) * parseFloat(price);
if (!isNaN(subTotal)) {
$tblrow.find('.subtot').val(subTotal.toFixed(2));
var grandTotal = {total};
$(".subtot").each(function () {
var stval = parseFloat($(this).val());
grandTotal += isNaN(stval) ? 0 : stval;
});
$('.grdtot').val(grandTotal.toFixed(2));
}
});
});
});
</script>
2
Answers
Does something like this work?
Could you try this? You can trigger an event using ‘.qty, .price’ in the table.
And I recommend using constants like
const qty = ...
instead of global variablevar qty= ...
inside of a block.