JSFiddle - React, Tailwind, and code Playground
by gregborbonus
HTML
<table>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>discount</th>
<th>Total</th>
</tr>
<tr>
<td>
<input id="txtQuantity1" type="text" /></td>
<td>
<input id="txtUnitprice1" type="text" /></td>
<td>
<input id="txtdiscount1" type="text" /></td>
<td>
<span id="lblTotal1"></span>
</td>
</tr>
<tr>
<td>
<input id="txtQuantity2" type="text" /></td>
<td>
<input id="txtUnitprice2" type="text" /></td>
<td>
<input id="txtdiscount2" type="text" /></td>
<td>
<span id="lblTotal2"></span>
</td>
</tr>
<tr>
<td colspan=3> </td>
<td id='grandTotal'></td>
</tr>
</table>
JavaScript
$(function () {
$("td :text").keyup(function () {
var quantity = $(this).parent().parent().find("td").eq(0).find(":text").val();
var price = $(this).parent().parent().find("td").eq(1).find(":text").val();
var discount = $(this).parent().parent().find("td").eq(2).find(":text").val();
if(isNaN($(this).val())) $(this).val($(this).val().substr(0,$(this).val().length-1)); // Block anything that is not a number.
quantity=(quantity !== "" && !isNaN(quantity))? quantity : 0; //make sure we're dealing with a number.
price=(price !== "" && !isNaN(price))? price*1 : 0; //make sure we're dealing with a number.
discount=(discount !== "" && !isNaN(discount))? discount*1 : 0; //make sure we're dealing with a number.
//if (quantity != "" && price != "" && discount != "") { //Zero is perfectly acceptable.
var total = parseFloat(quantity) * parseFloat(price) - parseFloat(discount);
$(this).parent().parent().find("td").eq(3).find("span").text(total);
//}
var gtotal=0; //Set GrandTotal to 0 initially.
$('[id^="lblTotal"]').each(function(){
gtotal= (gtotal + $(this).text()*1); // Add it, the *1 makes sure we're converting the text to number.
})
$('#grandTotal').html(gtotal); //Set the final result in the html
})
})