Knockout / jQuery : Simple List

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

by klenwell

HTML

<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<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>

<p>Selected: <input id="selected" type="text" />

JavaScript

var SimpleListModel = function(items) {
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function() {
        if (this.itemToAdd() != "") {
            this.items.push(this.itemToAdd());
            this.itemToAdd(""); 
        }
    }.bind(this);  // Ensure that "this" is always this view model
};
 
ko.applyBindings(new SimpleListModel(["Apple", "Berry", "Cherry"]));

$('option').on('click', function() {
    $('input#selected').val($(this).text());
});