JSFiddle - React, Tailwind, and code Playground
by wybiral
HTML
<table id="products">
<thead>
<tr><th>Quantity</th><th>Product</th><th>Cost</th></tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td colspan="2" style="text-align: right">
Expected total:
</td>
<td style="text-align: right">
<input type="text" id="expected"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
Calculated total:
</td>
<td style="text-align: right">
<input type="text" id="total" readonly />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
Difference:
</td>
<td style="text-align: right">
<input type="text" id="difference" readonly />
</td>
</tr>
<tr>
<td colspan="3" style="text-align: center">
<input type="button" value="Submit" id="submit" />
</td>
</tr>
</tfoot>
</table>
CSS
table {
margin-left: auto;
margin-right: auto;
width: 512px;
}
input[type="text"] {
background-color: #fff;
border: solid 1px #ccc;
font-family: monospace;
text-align: right;
}
input.units {
width: 50px;
}
input.cost {
width: 50px;
}
#expected {
width: 60px;
}
#total {
background-color: #eee;
width: 60px;
}
#difference {
background-color: #eee;
width: 60px;
}
span {
cursor: pointer;
}
JavaScript
function createProductLine(name, cost) {
var el = $('<tr></tr>');
var input = $('<input class="units" type="text" value="0">');
var cost = $('<input class="cost" type="text">').val(cost);
input.click(function() {
input.select();
});
el.append($('<td></td>').append(input));
el.append($('<td class="name"></td>').text(name));
el.append($('<td style="text-align: right"></td>').append(cost));
return el;
}
$(function() {
var products = $('#products > tbody');
products.append(createProductLine('SOME PRODUCT', 2.49));
products.append(createProductLine('SOME OTHER PRODUCT', 1.29));
products.append(createProductLine('JUNK AND STUFF', 5.99));
products.find('input').first().focus();
$('#products').on('change', 'input.cost', function() {
$(this).val(parseFloat($(this).val()).toFixed(2));
});
$('#products').on('change', '#expected', function() {
$(this).val(parseFloat($(this).val()).toFixed(2));
});
$('#products').on('change', 'input', function() {
var lines = products.find('tr'), total = 0.0;
lines.each(function(i, x) {
var $x = $(x);
var units = eval($x.find('.units').val());
var cost = eval($x.find('.cost').val());
total += units * cost;
});
$('#total').val(total.toFixed(2));
var expected = parseFloat($('#expected').val() || 0);
var difference = expected - total;
if (Math.abs(difference) >= 0.001) {
$('#submit').css({color: 'red'});
$('#difference').css({color: 'red'});
$('#difference').val(difference.toFixed(2));
} else {
$('#submit').css({color: 'black'});
$('#difference').css({color: 'green'});
$('#difference').val('0.00');
};
});
$('#submit').click(function() {
var difference = $('#difference').val();
if (difference != '0.00') {
if...