HOW TO ADD ITEM IN LIST BOX USING KNOCKOUTJS

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
 963  View(s)
Ratings:
Rate this:
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!!


  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to add item in list box using knockoutjs

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!