Reputation: 820
I have a dynamic HTML tbody
which I am creating on change event of a select option, so in my table, I have 3 input fields
ItemName
which is autocomplete
I am using jquery UI for that, So when the user selects any itemName I am populating that ItemName's data to corresponding fields of a table, all data I have is in JSON formatUnitQty
and enters something and on focus out of that I am doing some calculationDisc%
here I am doing 2-3 things, when a user enters some input and press enter
I am creating new row same as above with same functionality and some calculations are done and showed in a footer row I have named as Total
Disc%
and same calculation I am doingWhat my issue is
When user enters some data inside Disc%
and press tab
I am calling a function to calculate the data, suppose some times user by mistake press tab
and want to go back to Disc%
and create new row, so when I go back to Disc%
by pressing right Shift+tab
it doses some calculation as the function calcDiscount
runs again, sometimes if I goo back to edit the Disc%
field then also it runs the function calcDiscount
Also sometimes used by mistake put leave some field empty in table's input field I have tried to alert whenever the user leaves any empty field, but that too is not helping out
Please check out fiddle I am doing like below
$(document).keypress(function (event) {
const row = event.target.parentElement.parentElement
var keycode = event.keyCode || event.which;
if (keycode == '13') {
if (event.target.matches('[name=discPercentagetd]')) {
calcDiscount(event.target.parentElement.parentElement)
if ($(row).parent().find('tr').length - $(row).index() === 1) {
rowappend(event.target.parentElement.parentElement.parentElement)
}
}
}
});
document.addEventListener("keydown", function (event) {
const row = event.target.parentElement.parentElement
if (event.target.matches('[name=discPercentagetd]')) {
var keycode = event.keyCode || event.which;
if (keycode == '9') {
calcDiscount(event.target.parentElement.parentElement)
}
}
});
Please check out my fiddle I have commented all the lines there
Note-: after entering DIsc%
please go back to Disc%
after focusing out using rightShift+tab
and see the unitQty
in footer it auto increases
Upvotes: 0
Views: 90
Reputation: 2387
You need to set the all the values to 0 and then calculate the values by iterating through all the rows,
like this,
total = 0;
totalDiscountAmt = 0;
totalGstAmt = 0;
totalUnitQty = 0;
subtotal = 0;
$("#tableInvoice tbody tr").each(function() {
if (!$(event.target).val()) {
e.preventDefault();
return;
}
calc(this)
calcDiscount(this)
})
see the updated fiddle here https://jsfiddle.net/pLcexr6t/
Upvotes: 1