JSFiddle - React, Tailwind, and code Playground
by sushanth009
HTML
<table>
<tr>
<th width=200px>Description</th>
<th width=60px>Unit Cost</th>
<th width=60px>Quantity</th>
<th width=60px>Total</th>
</tr>
<tr>
<td width=200px>PCI Wireless Card</td>
<td width=60px><input type="text" value="15.99" class="price" /></td>
<td width=60px><input type="text" value="1" class="quantity" /></td>
<td width=60px><label class="subtotal" >15.99</label> </td>
</tr>
<tr>
<td width=200px>SATA Cable</td>
<td width=60px><input type="text" value="2.50" class="price" /></td>
<td width=60px><input type="text" value="1" class="quantity" /></td>
<td width=60px><label class="subtotal" >2.50</label></td>
</tr>
<tr>
<td width=200px>------</td>
<td width=60px>-------</td>
<td width=60px><label class="totalquantity" >2</label></td>
<td width=60px><label class="grandtotal" >17.49</label></td>
</tr>
</table>
CSS
table
{
border: 1px solid orange
}
th
{
padding : 3px;
font-weight:bold;
border: 1px solid orange
}
td
{
padding : 3px;
border: 1px solid orange;
}
input[type="text"]
{
width : 50px;
}
JavaScript
$(function() {
CalculateTotal();
// Adding the change events for the Price and
// quantity fields only..
// Changing the total should not affect anything
$('.quantity , .price').on('change', function() {
UpdateTotals(this);
});
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $container.find('.price').val();
var subtotal = parseInt(quantity) * parseFloat(price);
$container.find('.subtotal').text(subtotal.toFixed(2));
}
function CalculateTotal(){
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function(i){
grandTotal += parseFloat($(lineTotals[i]).text()) ;
totalQuantity += parseInt($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal ).toFixed(2) );
}