The value of total price changes on the first row only

The JS code is relatively simple. All it needs to do is to lop through each row of the <tbody> section, get the 5th, 6th, and 7th <td> from each row, and get the number from each input to perform the calculation.

            var table = document.querySelector("table");
            var rows = table.querySelectorAll("tbody tr");
            rows.forEach(function calcRow(row) {
                var unitsField = row.querySelector("td:nth-of-type(5) input");
                var quantityField = row.querySelector("td:nth-of-type(6) input");
                var totalField = row.querySelector("td:nth-of-type(7) input");
                var units = Number(unitsField.value);
                var quantity = Number(quantityField.value);
                totalField.value = units * quantity;
            });

For the grand total it’s just a matter of looping through the rows again, and adding up the totals.

            var grandTotal = Array.from(rows).reduce(function calcTotal(total, row) {
                var totalField = row.querySelector("td:nth-of-type(7) input");
                return total + Number(totalField.value);
            }, 0);
            var footerRow = table.querySelector("tfoot tr");
            var grandTotalField = footerRow.querySelector("td:last-of-type input");
            grandTotalField.value = grandTotal;

Here’s the full scripting code that solves all of the problems for you.

        function calculateTotal() {
            var table = document.querySelector("table");
            var rows = table.querySelectorAll("tbody tr");
            rows.forEach(function calcRow(row) {
                var unitsField = row.querySelector("td:nth-of-type(5) input");
                var quantityField = row.querySelector("td:nth-of-type(6) input");
                var totalField = row.querySelector("td:nth-of-type(7) input");
                var units = Number(unitsField.value);
                var quantity = Number(quantityField.value);
                totalField.value = units * quantity;
            });
            var grandTotal = Array.from(rows).reduce(function calcTotal(total, row) {
                var totalField = row.querySelector("td:nth-of-type(7) input");
                return total + Number(totalField.value);
            }, 0);
            var footerRow = table.querySelector("tfoot tr");
            var grandTotalField = footerRow.querySelector("td:last-of-type input");
            grandTotalField.value = grandTotal;
        }
        var table = document.querySelector("table");
        table.addEventListener("change", calculateTotal);
        var button = document.querySelector("tfoot [type=button]");
        button.addEventListener("click", calculateTotal);
1 Like