JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<table id="table1" cellspacing="0" cellpadding="0" border="0">
<tr>
<th style="width:150px">Product</th>
<th>Price ($)</th>
<th>Quantity</th>
<th>Amount ($)</th>
</tr>
<tbody data-bind='template: {name: "orderTemplate", foreach: lines}'></tbody>
</table>
<script type="text/html" id="orderTemplate">
<tr>
<td><select data-bind='options: products,
optionsText: "name",
optionsCaption:"--Select--",
value: product'>
</select>
</td>
<td>
<span data-bind='text:price' ></span>
</td>
<td>
<input data-bind='value:quantity' />
</td>
<td ><span data-bind='text:$parent.formatCurrency(subtotal())'></span></td>
</tr>
</script>
CSS
body {
font-family: arial;
font-size: 14px;
}
.liveExample {
padding: 1em;
background-color: #EEEEDD;
border: 1px solid #CCC;
max-width: 655px;
}
.liveExample input {
font-family: Arial;
}
.liveExample b {
font-weight: bold;
}
.liveExample p {
margin-top: 0.9em;
margin-bottom: 0.9em;
}
.liveExample select[multiple] {
width: 100%;
height: 8em;
}
.liveExample h2 {
margin-top: 0.4em;
font-weight: bold;
font-size: 1.2em;
}
JavaScript
var _products = [
{
"name": "1948 Porsche 356-A Roadster",
"price": 53.9,
"quantity": 1
},
{
"name": "1948 Porsche Type 356 Roadster",
"price": 62.16,
"quantity": 2
},
{
"name": "1949 Jaguar XK 120",
"price": 47.25,
"quantity": 1
},
{
"name": "1952 Alpine Renault 1300",
"price": 98.58,
"quantity": 1
},
{
"name": "1952 Citroen-15CV",
"price": 72.82,
"quantity": 1
},
{
"name": "1956 Porsche 356A Coupe",
"price": 98.3,
"quantity": 1
},
{
"name": "1957 Corvette Convertible",
"price": 69.93,
"quantity": 1
}];
function formatCurrency(value) {
//alert(value.toFixed(2));
return "$" + value.toFixed(2);
}
var CartLine = function () {
var self = this;
self.products = ko.observableArray(_products);
self.product = ko.observable(1);
self.price = ko.observable(1);
self.quantity = ko.observable(1);
self.product.subscribe(function(item){
if(!item)
{
self.price(0);
self.quantity(0);
return;
}
self.price(item.price);
self.quantity(item.quantity);
});
self.subtotal = ko.computed(function () {
return self.price() * self.quantity();
},self);
};
var Cart = function () {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.formatCurrency = formatCurrency;
};
ko.applyBindings(new Cart());