Reputation: 467
In the below I have a table row where a calculation happens upon input in .quantity
and the result of that calculation is placed in .amount2
. This works just fine and works as you see below.
<tr class="manifest-row">
<td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form.ProductCode}}</td>
<td width = 32.5% class="description">{{form.DescriptionOfGoods}}</td>
<td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form.UnitQty}}</td>
<td width = 12.5% class="unitType">{{form.Type}}</td>
<td width = 10.5% class="price" oninput="calculate(this)">{{form.Price}}</td>
<td width = 12.5% class="amount2">{{form.Amount}}</td>
</tr>
JS
function calculateUnit(el) {
// Find the row containing this cell
var row = el.closest("tr");
// Get the quantity from the `input` in the `.quantity` cell in this row
var unitQty = el.querySelector('.quantity input').value;
// Get the price from the `input` in this cell (could use `e.target` instead)
var price = row.querySelector('.price input').value;
// Do the calculation, assign to the `input` in the `.amount` cell in this row
var lineTotal = unitQty * price;
row.querySelector('.amount2 input').value = lineTotal;
}
The issue is that there can be many rows, and I have a separate function which sums all the values in the inputs where class is .amount2
and places that sum in a field #id_InvoiceTotal
. But this function below does not trigger properly on input because it is being filled instead by the function above. So how can I make the function above trigger the function below? I've seen .trigger()
in my online searches but I don't understand how to apply it here.
<script>
$(document).on("input", ".amount2", function() {
var total = 0;
var i = 0;
$('#form_set .amount2').each(function() {
total += parseInt($('#id_form-'+(i)+'-Amount').val());
i++;
$('#id_InvoiceTotal').val(total);
})
});
</script>
Upvotes: 0
Views: 49
Reputation: 2731
You can do it in the same function with just two additional statements like this :
function calculateUnit(el) {
let total = 0;
var row = el.closest("tr");
var unitQty = el.querySelector('.quantity input').value;
var price = row.querySelector('.price input').value;
var lineTotal = unitQty * price;
row.querySelector('.amount2 input').value = lineTotal;
document.querySelectorAll(".amount2 input").forEach(function(item){
total += item.value / 1;
});
document.querySelector("#id_InvoiceTotal").value = total;
}
Upvotes: 1