2
votes

I'm trying to set options on a selectbox with an observable array. I can get the options to populate but the array is appearing as one option and has no value too now that I look at it.

Here's the fiddle and code below:

var Model = function (properties) {
    this.AvailableLenders = ko.observableArray();

    this.ModifyLenders = function (newProperties) {
        var lenders = [],
            count = 0;

        ko.utils.arrayForEach(newProperties || properties, function (item) {
            var lender = item.Lender;

            if (lender) {
                if (lenders.indexOf(lender) == -1) {
                    lenders[count] = lender;

                    count++;
                }
            }
        });

        this.AvailableLenders.removeAll();

        return this.AvailableLenders.push(lenders.sort());
    };

    this.ModifyLenders();
};

ko.applyBindings(new Model([{Lender: "ASB"}, {Lender: "ANZ"}]));

HTML:

<select multiple="multiple" name="Lender" id="Lender" data-bind="options: AvailableLenders, optionsCaption: 'Please select a lender'"></select>
1

1 Answers

1
votes

I found the problem .

The problem is you are pushing Lender array in a single index of AvailableLenders array

var Model = function (properties) {
this.AvailableLenders = ko.observableArray();

this.ModifyLenders = function (newProperties) {
    var lenders = [],
        count = 0;

    ko.utils.arrayForEach(newProperties || properties, function (item) {
        var lender = item.Lender;

        if (lender) {
            if (lenders.indexOf(lender) == -1) {
                lenders[count] = lender;

                count++;
            }
        }
    });

    this.AvailableLenders.removeAll();

    console.log("lenders ", lenders)
    console.log("lenders.sort() ", lenders.sort())

The I made below changes . Now you can understanding why it is happening

Add these two lines in your fiddle and check what is happening

    this.AvailableLenders.push(lenders[0]);
    this.AvailableLenders.push(lenders[1]);
    return this.AvailableLenders.push(lenders.sort());
   };

  this.ModifyLenders();
  };

 ko.applyBindings(new Model([{
  Lender: "ASB"
 }, {
  Lender: "ANZ"
 }]));

Mark it as answer