2

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.