Juanda
Juanda

Reputation: 49

Knockout bind select with custom object with observable properties

I'm trying to bind a <select> with Knockout. In my ViewModel I have 2 different objects, each with observable properties.

First object is Property which has a headquarter_id as a ko.observable(). Second object is Headquarter which has an id and a name, both as ko.observable().

What I'm trying to do, is bind a select with an ko.observableArray() of Headquarter objects, like this:

<select id="headquarters" data-bind="options: HeadquarterOptions, optionsText: name, optionsValue: id, optionsCaption: '--Select--', value: Property().headquarter_id"></select>

But I keep getting:

Uncaught ReferenceError: Unable to process binding "options: function (){return HeadquarterOptions }"
Message: id is not defined

Here is how my ViewModel looks like:

var Property = function () {
    var self = this;
    self.headquarter_id = ko.observable();
}

var Headquarter = function (id, name) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
}

var headquarterOptions = [
        new Headquarter(1, "hq 1"),
        new Headquarter(2, "hq 2"),
        new Headquarter(3, "hq 3"),
    ]

var PropertiesViewModel = function (app, dataModel) {
    var self = this;
    self.Property = ko.observable(new Property());
    self.HeadquarterOptions = ko.observableArray(headquarterOptions);
}
    
ko.applyBindings(PropertiesViewModel);

How can I achieve this?
Here's my current fiddle: http://jsfiddle.net/juandozco/dzwnb05b/

Upvotes: 0

Views: 417

Answers (2)

Ibrahim Ahmed
Ibrahim Ahmed

Reputation: 2345

There you go http://jsfiddle.net/dzwnb05b/4/

<select class="form-control" id="headquarter" data-bind="options: HeadquarterOptions, optionsText: 'name', optionsValue: 'id', optionsCaption: '--Select--', value: Property().headquarter_id"></select>

You were missing single quotation marks around name and id.

Upvotes: 3

Yevgen Safronov
Yevgen Safronov

Reputation: 4033

optionsValue and optionsText should be declared as functions instead of values (http://knockoutjs.com/documentation/options-binding.html):

optionsText: function(item) {return item.name; }
optionsValue: function(item){ return item.id; }

Check out the updated fiddle: http://jsfiddle.net/dzwnb05b/3/

Upvotes: 2

Related Questions