Knockoutjs.com - Better list example
http://knockoutjs.com/examples/betterList.html
by ernestohs
HTML
<script src="http://knockoutjs.com/js/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/js/knockout-1.2.1.js"></script>
<div class='liveExample'>
<form data-bind='submit:addItem'>
Add item: <input data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' type='text' />
<button data-bind='enable: itemToAdd().length > 0' type='submit'>Add</button>
</form>
<p>Your values:</p>
<select data-bind='options:allItems, selectedOptions:selectedItems' multiple='multiple' height='5'> </select>
<div>
<button data-bind='click: removeSelected, enable: selectedItems().length > 0'>Remove</button>
<button data-bind='click: function() { allItems.sort() }, enable: allItems().length > 1'>Sort</button>
</div>
</div>
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; }
JavaScript
// In this example, betterListModel is a class, and the view model is an instance of it.
// See simpleList.html for an example of how to construct a view model without defining a class for it. Either technique works fine.
var betterListModel = function() {
this.itemToAdd = new ko.observable("");
this.allItems = new ko.observableArray(["Fries", "Eggs Benedict", "Ham", "Cheese"]); // Initial items
this.selectedItems = new ko.observableArray(["Ham"]); // Initial selection
this.addItem = function() {
if ((this.itemToAdd() != "") && (this.allItems.indexOf(this.itemToAdd()) < 0)) // Prevent blanks and duplicates
this.allItems.push(this.itemToAdd());
this.itemToAdd(""); // Clear the text box
}
this.removeSelected = function() {
this.allItems.removeAll(this.selectedItems());
this.selectedItems([]); // Clear selection
}
};
ko.applyBindings(new betterListModel());