That calculation already exist in your code! Just re-use it.
I made a function with the part of your code where you were calculating the total...
And I called it after the td
is appended AND after one has been removed.
About the remove function... It should not be in the colorddRow
function. It's an event handler declaration. If inside, everytime you add a row, it registers the handler again.
// The total function
function calculateTotal(){
// Total Sum
var td = document.querySelectorAll(
"#dataTable1-color-parts > tbody > tr > td:last-child"
);
var total = 0; //colpartssum;
for (var i = 0; i < td.length; i++) {
total += parseInt(td[i].innerText);
}
document.getElementById("col-parts-total-qty").innerText = total;
console.log(total);
}
function colorddRow() {
var colorpartsrows = "";
var colparts = $("#color-part-list").val();
// Sum of the rejected colors qty in every row
var colpartssum = $("#color-part-list :selected").length;
// Creates the dynamic table Onclick
colorpartsrows +=
"<tr><td><button class=removeDepIt>Delete</button></td><td>" +
colparts +
"</td><td>" +
colpartssum +
"</td></tr>";
// Adds the rows to the dynamic table
$(colorpartsrows).appendTo("#dataTable1-color-parts tbody");
calculateTotal(); // Calculate the total here
} // The add row function ends here.
// Delete Rows Onclick
$("#dataTable1-color-parts").on("click", ".removeDepIt", function () {
var row = $(this).closest("tr");
var prev = row.prev();
row.remove();
calculateTotal(); // Calculate the total here
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…