# How to calculate html table column data Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to calculate html table column data without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a Dynamically created HTML table, when page loads I am creating the first row having following columns `ItemName`,`I Code`,`MRP`,`Price`,`UnitQty`,`Disc%`,`DiscAmt`,`Gst%`,`GstAmt` and `TotalAmt`

`ItemName` is autocomplete field, So user is selecting item name by typeing and when user focus out I am populating some respective fields ,When user Types inside `UnitQty` field I am calculating some values and populating according to that in respective fields on `keyup` event all this is happening in HTML table

outside the tabel I have a Input Field `SubTotal` which is I am getting with Some calculation i.e `price * UnitQty` so for respective table row There is a Total Amt column where I have to populate `(price * UnitQty) +GstAmt +DiscAmt` but currently I am populating `price * UnitQty` I will do that later

What My issue is

So below is a `subTotal` Input field where I am populating `price * UnitQty` of each row so I am storing the values in global variable and then adding the current variable into that but when I type suppose 2 and price is 100 it equals to 200 then I am removing 2 and writing 2 at that time it is adding the previous 200 and current 300 and populating 500 I know this is because of `keyup` it is adding previous value also but that’s not correct

There is no column for subtotal in HTML table that’s why I am storing it in a variable

```function format(number, decimals = 2) {
const fixed = parseFloat(number).toFixed(decimals);
const [float, dec] = fixed.split('.')
const intFormatted = (+float)
return intFormatted + (dec ? '.' + dec : '');
}

var tableData = {};
var tabledata = {
"ALMOND CHBAR~2402": {
"itemName": "ALMOND CHBAR",
"itemCode": "2402",
"costPrice": 20.0,
"gstPercentage": 14.5,
"unitCode": "NOS",
"mrp": 30.0
},
"A BR SB EX~333": {
"itemName": "A BR SB EX",
"itemCode": "333",
"costPrice": 1.0,
"gstPercentage": 0.0,
"unitCode": "NOS",
"mrp": 1.0
}
}

populateData(tabledata)

function rowappend(tbody) {

const markup =
`<tr>
<td>
<input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
</td>
<td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="tel"  id="purRatetd"  class="form-control commantd"name="purRatetd"></td>
<td>
<input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
</td>

<td>
<input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" value="0.00">
</td>
<td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<input type="hidden" name="unittd" id="unittd" class="form-control commantd">
<td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn" ></i></td>

</tr>`

\$(tbody).append(markup);
setTimeout(() => \$("[name=itemNametd]", tbody).last().focus(), 100);

var autoCompleteData = Object.keys(tableData);
\$("[name=itemNametd]", tbody).last().autocomplete({
source: autoCompleteData,
autoSelectFirst: true,
autoFocus: true

}).data('tableData', tableData);

}

function getValues(row) {
const search = (\$('[name=itemNametd]', row).val()).toString()

var data = \$('[name=itemNametd]', row).data('tableData');
const value = data[search];

if (value) {
CostPrice = value.costPrice;
\$(row).find("[name=itemCodetd]").val(value.itemCode);
\$(row).find("[name=mrptd]").val(format(value.mrp));
\$(row).find("[name=purRatetd]").val(format(CostPrice));
\$(row).find("[name=unittd]").val(value.unitCode);
\$(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
\$("[name=purRatetd]").focus();
}

}

\$(document).on("keyup", "[name=purRatetd]", function(e) {
const row = e.target.parentElement.parentElement
var unitQuantity = \$(row).find("[name=unitQtytd]").val();

var purchaseRate = \$(row).find("[name=purRatetd]").val();
var mrp = \$(row).find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate)) || 0;

\$(row).find("[name=totalAmttd]").val(format(totalAmount));

});
var subTotalAmt = 0;
\$(document).on("keyup", "[name=unitQtytd]", function(e) {

const row = e.target.parentElement.parentElement
unitQuantity = \$(row).find("[name=unitQtytd]").val();

purchaseRate = \$(row).find("[name=purRatetd]").val();
mrp = \$(row).find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate)) || 0;

subTotalAmt += totalAmount || 0

\$(row).find("[name=totalAmttd]").val(format(totalAmount));
\$("#subTotalInput").val(format(subTotalAmt));
});

const row = event.target.parentElement.parentElement

var keycode = event.keyCode || event.which;
if (keycode == '13') {
if (!\$(event.target).val()) {
e.preventDefault();
return;
}
const row = e.target.parentElement.parentElement
if (event.target.matches('[name=discPercentagetd]')) {
if (\$(row).parent().find('tr').length - \$(row).index() === 1) {
rowappend(event.target.parentElement.parentElement.parentElement)
}
}
}

});

\$(document).on("focusout", "[name=itemNametd]", function(e) {
const row = e.target.parentElement.parentElement
getValues(e.target.parentElement.parentElement)
});

function populateData(data) {
tableData = Object.assign({}, data);
var autoCompleteData = Object.keys(data);
rowappend(\$('tbody', '#tableInvoice'));

}

});```
```<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row tableGrn" id="commonDvScroll">
<table class="table table-bordered" id="tableInvoice">
<tr>
<th id="itemNameth" class="commanth">Item Name</th>
<th id="itemCodeth" class="commanth">I Code</th>
<th id="mrpth" class="commanth">MRP</th>
<th id="purRateth" class="commanth">Price</th>
<th id="unitQtyth" class="commanth">Unit Qty</th>
<th id="discPercentageth" class="commanth">Disc %</th>
<th id="discAmtth" class="commanth">Disc Amt</th>
<th id="gstPercentageth" class="commanth">GST %</th>
<th id="gstAmtth" class="commanth">GST Amt</th>
<th id="totalAmtth" class="commanth">Total Amt</th>

</tr>
<tbody>
</tbody>

</table>

</div>
<div class="form-row">

<div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-2">
<label for="subTotalInput">Sub Total</label>
<div class="input-group">
<input type="tel" class="form-control" aria-label="Text input with dropdown button" name="subTotalInput" id="subTotalInput" readonly="readonly" tabindex="-1">

</div>
</div>
</div>```

Note-: Please don’t get confused by TotalAmt column that one is for other usage which I will do by adding all the amounts

For now I have been stuck in calculating subTotal row wise and populate in a Input field

On press of `enter` at `Disc%` it will create a new row

Please replace your code with below code

```\$(document).on("keyup", "[name=purRatetd],[name=unitQtytd]", function(e) {
var unitQuantity = \$(this).closest('tr').find("[name=unitQtytd]").val();
var purchaseRate = \$(this).closest('tr').find("[name=purRatetd]").val();
var unitQuantity = unitQuantity ? unitQuantity : 1;
var mrp = \$(this).closest('tr').find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));
\$(this).closest('tr').find("[name=totalAmttd]").val(totalAmount);
var subTotal = 0;
\$("[name=totalAmttd]").each(function(){
var curVal = parseFloat(\$(this).val());
if(curVal){
subTotal = curVal + subTotal;
}
});
\$("#subTotalInput").val(subTotal);
});
```

N:B – you are using id in input fields which will repeat again and again after apending so avoid using id and name…In entire code you can use class instead of name or id……class name can be same but id and name can’t be same in multiple fields

We are here to answer your question about How to calculate html table column data - If you find the proper solution, please don't forgot to share this with your team members.