JSFiddle - React, Tailwind, and code Playground
HTML
<table>
<tr>
<td>Product1</td>
<td>
<input type="hidden" name="price" value="1.99" />
£1.99
</td>
<td>
<input class="quantity" type="text" name="quantity" value="0" />
<input class="add-quantity" type="button" value="+" />
<input class="remove-quantity" type="button" value="-" />
</td>
<td>
£<span class="cost">0</span>
</td>
<td>
<input class="remove-item" type="button" value="Delete" />
</td>
</tr>
<tr>
<td>Product2</td>
<td>
<input type="hidden" name="price" value="2.99" />
£2.99
</td>
<td>
<input class="quantity" type="text" name="quantity" value="0" />
<input class="add-quantity" type="button" value="+" />
<input class="remove-quantity" type="button" value="-" />
</td>
<td>
£<span class="cost">0</span>
</td>
<td>
<input class="remove-item" type="button" value="Delete" />
</td>
</tr>
<tr>
<td>Product3</td>
<td>
<input type="hidden" name="price" value="3.99" />
£3.99
</td>
<td>
<input class="quantity" type="text" name="quantity" value="0" />
<input class="add-quantity" type="button" value="+" />
<input class="remove-quantity" type="button" value="-" />
</td>
<td>
£<span class="cost">0</span>
</td>
<td>
<input class="remove-item" type="button" value="Delete" />
</td>
</tr>
</table>
<p>Subtotal: £<span class="sub-total">0.00</span></p>
<p>VAT @ 20%: £<span class="vat">0.00</span></p>
<p>Total Cost: £<span class="total-cost">0.00</span></p>
JavaScript
$(function() {
var updateSubtotal = function() {
var $subTotal = $('.sub-total');
var $vat = $('.vat');
var $total = $('.total-cost');
var $rows = $('tr');
var subtotal = 0;
$rows.each(function(index, row) {
var $row = $(row);
var $price = $row.find('input[name=price]');
var $quantity = $row.find('input[name=quantity]');
subtotal += parseFloat($price.val()) * parseInt($quantity.val(), 10);
});
$subTotal.text(subtotal.toFixed(2));
$vat.text( ((subtotal * 20) / 100).toFixed(2));
$total.text( (parseFloat($vat.text()) + subtotal).toFixed(2) );
};
var updateCost = function($row, quantity) {
var $price = $row.find('input[name=price]');
var $cost = $row.find('.cost');
$cost.text( (parseFloat($price.val()) * quantity).toFixed(2) );
updateSubtotal();
};
$('.add-quantity').click(function() {
var $row = $(this).parents('tr');
var $quantity = $row.find('.quantity');
var quantity = parseInt($quantity.val(), 10);
if (quantity < 10) {
quantity++;
$quantity.val(quantity);
updateCost($row, quantity);
}
});
$('.remove-quantity').click(function() {
var $row = $(this).parents('tr');
var $quantity = $row.find('.quantity');
var quantity = parseInt($quantity.val(), 10);
if (quantity > 0) {
quantity--;
$quantity.val(quantity);
}
updateCost($row, quantity);
});
$('.quantity').keyup(function() {
var $row = $(this).parents('tr');
var quantity = parseInt($(this).val(), 10);
if (isNaN(quantity)) {
quantity = 0;
}
if (quantity < 0) {
quantity = 0;
} else if (quantity > 10) {
quantity =...