0
votes

I am having a day with knockout. Here is my simplified VM:

function UserRecruitingViewModel(apiBaseUrl, userId) {
    var self = this;
    self.orgs = ko.observableArray();
    //ddl org view switcher stuff
    self.orgDdl = ko.observableArray();
    self.selectedOrg = ko.observable();
    var DropdownOrg = function (name, orgId) {
        this.name = name;
        this.orgId = orgId;
    };
    //...snip ajax get to pull data...//
}

Note I have this line in there:

self.selectedOrg = ko.observable();

On my page I have this drop down list:

<select 
data-bind="options: $root.orgDdl, optionsText: 'name', optionsValue: $root.selectedOrg">
</select>

For easier reading, the data-bind values:

data-bind="
    options: $root.orgDdl, 
    optionsText: 'name', 
    optionsValue: $root.selectedOrg"

This is not working. If I have my select element like without the optionsValue binding in there it will bind the list with the value I got from the GET request.

I am getting an error in my console saying:

Unable to process binding "text: function (){return selectedOrg() }"
Message: selectedOrg is not defined

I am confused since I do have the selectedOrg observable set on my VM.

2

2 Answers

1
votes

If selectedOrg is to get selected option's object, then use like selectedOption in my sample.

ViewModel

var optionModel = function(id,name){
    var self = this;
    self.id = id;
    self.name = name;
}

var viewModel = function(){
    var self = this;
    self.options = [
        new optionModel(1,"First"),
        new optionModel(2,"Second")
    ];
   self.selectedOptionId = ko.observable(0);
   self.selectedOption = ko.computed(function(){
        return ko.utils.arrayFirst(self.options, function(item){
            return item.id === self.selectedOptionId();
        });
    });
}

ko.applyBindings(new viewModel());

HTML Bindings

<select data-bind="options: options, 
                   optionsText: 'name',
                   optionsValue: 'id', 
                   value: selectedOptionId,
                   optionsCaption:'Choose.....'">
</select>

Above code are for simple options binding with knockout. For this question the model is not well defined, and the reason optionsValue you are using is not clear.

Here is sample jsfiddle for reference(the sample based on sample option model as your question is not clear)

0
votes

You want just plain value in your binding rather than optionsValue. value specifies what observable gets the result of the selection; optionsValue is used if you want value to be set to one particular property of an object, rather than the object itself. Assuming you want selectedOrg() to contain the entire DropdownOrg object that you select, you don't need optionsValue.