How to add item in list box using knockoutjs

I am trying to add item in list box

This is my view code:


<div class="container" style="max-width: 400px; border: 1px solid #e2e2e2; padding: 50px; margin-top: 30px">
        <br />
        <div class="row">
            <div class="row">
                <div class="col-md-4">
                    Item Name:
                </div>
                <div class="col-md-6">
                    <input type="text" class="form-control" data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary" data-bind="enable: itemToAdd().length > 0 ">Add</button>
                </div>
            </div>
            <br />
            <div class="row">
                <div class="col-md-4">
                    Item List:
                </div>
                <div class="col-md-8">
                    <select multiple="multiple" class="form-control" style="height: 100px" data-bind="options: items"></select>
                </div>
            </div>
        </div>
    </div>

 

And this is my script code:

$(function () {
   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);
     };
     ko.applyBindings(new SimpleListModel());
 });

This is my complete code but item is not add in list box. I don’t know where is create problem of my code. Please solve my problem as soon as possible.

Thanks in advance!!


Last updated:2/18/2015 7:17:36 AM

1 Answers

Pravesh Singh
Pravesh Singh

You missed to call function addItem on click button like this

<button type='submit' class='btn btn-primary' data-bind='enable:
itemToAdd().length > 0,click: addItem'>Add</button>

Answer