Knockoutjs.com - Simple list example

http://knockoutjs.com/examples/simpleList.html

by Sandeep Kumar

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div id='dvKnockout'> 
    
<form data-bind="submit: addItem">
    New item:
    <input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
    <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
    <p>Your items:</p>
    <select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
    
</div>

CSS

body { font-family: arial; font-size: 14px; }
#dvKnockout { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
#dvKnockout input { font-family: Arial; }
#dvKnockout b { font-weight: bold; }
#dvKnockout p { margin-top: 0.9em; margin-bottom: 0.9em; }
#dvKnockout select[multiple] { width: 100%; height: 8em; }
#dvKnockout h2 { margin-top: 0.4em; }

JavaScript

var ColorListModel = function(items) {
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function() {
        if (this.itemToAdd() != "") {
        		// Adds the item to the "items" observableArray updates associated UI as well.
            this.items.push(this.itemToAdd());
            // Clears the "itemToAdd", that'll clear the textbox.
            this.itemToAdd("");
        }
    }.bind(this);  // Ensure that "this" is always this view model
};
 
ko.applyBindings(new ColorListModel(["Red", "Blue", "Black"]));