JSFiddle - React, Tailwind, and code Playground
by mrfunnel
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<form class="giftListEditor" data-bind="submit: save">
<!-- Our other UI elements, including the table and ‘add’ button, go here -->
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<table>
<tbody data-bind="foreach: gifts">
<tr>
<td>Gift name: <input data-bind="value: Title"/></td>
<td>Price: $ <input data-bind="value: Price"/></td>
<td>Company: <select data-bind="options: $root.companies, optionsText: 'Name', value: Company"/></td>
<td><a href="#" data-bind="click: function() { viewModel.removeGift($data) }">Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
</form>
JavaScript
// Fake data
var initialData = [
{ Title: 'Item 1', Price: 56, Company: { Id: 1, Name: "Comp 1" } },
{ Title: 'Item 2', Price: 56, Company: { Id: 2, Name: "Comp 2" } },
{ Title: 'Item 3', Price: 56, Company: { Id: 2, Name: "Comp 2" } }
];
var initialCompanies = [
{ Id: 1, Name: "Comp 1" },
{ Id: 2, Name: "Comp 2" },
{ Id: 2, Name: "Comp 3" }
];
var viewModel = {
gifts: ko.observableArray(initialData),
companies: ko.observableArray(initialCompanies),
addGift: function() {
this.gifts.push({
Title: "",
Price: "",
Company: { Id: "", Name: "" }
});
},
removeGift: function(gift) {
this.gifts.remove(gift);
},
save: function() {
console.log(ko.toJS(viewModel.gifts));
}
};
ko.applyBindings(viewModel, document.body);