JSFiddle - React, Tailwind, and code Playground
by neebz
HTML
<script src="http://knockoutjs.com/js/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/js/knockout-1.1.2.js"></script>
<table>
<tr>
<th>Qty</th>
<th>Description</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
<tbody data-bind="template: { name: 'rowTemplate', foreach: theItems }">
</tbody>
</table>
<a id="addItem" data-bind="click: addItem" href="#">Add Item</a>
<div>Total: <span data-bind="text: megaTotal"></span></div>
<script type="text/html" id="rowTemplate">
<tr>
<td><input data-bind="value: qty"/></td>
<td><input data-bind="value: description"/></td>
<td><input data-bind="value: cost"/></td>
<td><span data-bind="text: total"></span></td>
<td><a href="#" data-bind="click: function () { viewModel.removeItem($data) }"> X </a></td>
</tr>
</script>
CSS
table th {
font-weight: bold;
}
table td {
padding: 0.3em;
}
JavaScript
try
{
function createNewItem() {
var theItem = {
qty: ko.observable(""),
description: ko.observable(""),
cost: ko.observable("")
}
theItem.total = ko.dependentObservable(function () {
var total = parseFloat(this.qty()) * parseFloat(this.cost());
if (total != NaN)
{
return total
}
else
{
return "";
}
}, theItem);
return theItem;
}
var initialData = [];
viewModel = {
theItems: ko.observableArray(initialData),
addItem: function () {
this.theItems.push(createNewItem());
},
removeItem: function(theItem) {
this.theItems.remove(theItem);
}
};
viewModel.megaTotal = ko.dependentObservable(function() {
var megaTotal = 0;
for (var i = 0; i < this.theItems().length; i++)
{
var bah = parseFloat(this.theItems()[i].total());
if (bah != NaN) megaTotal = megaTotal + bah;
}
return megaTotal;
}, viewModel);
ko.applyBindings(viewModel);
}
catch (e)
{
alert (e);
}