Knockoutjs.com - Better list example
http://knockoutjs.com/examples/betterList.html
by Igor Cuckovic
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div class='liveExample'>
<form data-bind="submit:addItem">
Add item: <input type="text" data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
</form>
<p>Your values:</p>
<select multiple="multiple" height="5" data-bind="options:allItems, selectedOptions:selectedItems"> </select>
<div>
<button data-bind="click: removeSelected, enable: selectedItems().length > 0">Remove</button>
<button data-bind="click: sortItems, 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
var betterListModel = function () {
var itemToAdd = ko.observable("");
var allItems = ko.observableArray(["Fries", "Eggs Benedict", "Ham", "Cheese", "Hello"]); // Initial items
var selectedItems = ko.observableArray(["Ham"]); // Initial selection
var addItem = function () {
if ((itemToAdd() != "") && (allItems.indexOf(itemToAdd()) === -1)) // Prevent blanks and duplicates
allItems.push(itemToAdd());
itemToAdd(""); // Clear the text box
};
var removeSelected = function () {
allItems.removeAll(selectedItems());
selectedItems([]); // Clear selection
};
var sortItems = function() {
allItems.sort();
};
return {
itemToAdd: itemToAdd,
allItems: allItems,
selectedItems: selectedItems,
addItem: addItem,
removeSelected: removeSelected,
sortItems: sortItems
}
};
ko.applyBindings(betterListModel());