Reputation: 2372
The function below does calculate when a number changes in each row, but at start up, I'd like to have it calculate all columns and rows and put the total of each row.
function sum_row_qty(el) {
let rowTotal = 0
if (el) {
let parent = el.closest("tr")
parent.querySelectorAll('.size_qty').forEach(function(e) {
rowTotal += parseFloat(e.value)
})
parent.querySelector('.qty').value = rowTotal
}
/*else {
$("#tableRows tr").each(function(row) {
let sizes = row.querySelectorAll('.size_qty').forEach(function(e) {
rowTotal += parseInt(sizes);
});
}
}*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tableRows">
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
</tbody>
</table>
Thanks in advance!
Upvotes: 0
Views: 55
Reputation: 780673
In the else
block, call your function in a loop over an input in each row of the table.
Then call your function with no argument when the page is loaded, and it will execute this branch.
function sum_row_qty(el) {
let rowTotal = 0
if (el) {
let parent = el.closest("tr")
parent.querySelectorAll('.size_qty').forEach(function(e) {
rowTotal += parseFloat(e.value)
})
parent.querySelector('.qty').value = rowTotal
} else {
document.querySelectorAll("#tableRows > tr > td:first-child input").forEach(sum_row_qty);
}
}
window.addEventListener("load", () => sum_row_qty());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tableRows">
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
<tr>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="6" onchange="sum_row_qty(this);"></td>
<td><input class="size_qty" type="number" min="0" name="numberInputs" value="3" onchange="sum_row_qty(this);"></td>
<td><input type="number" min="0" class="qty" name="numberInputs" value="" readonly="true"></td>
</tr>
</tbody>
</table>
Upvotes: 2