0

I am trying to bind dropdown with observable array and setting the selected item based on a condition but the selected value is not getting updated.

Code for the same is:

function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}

var viewModel = function(){
var self= this;
self.test = ko.observable('a'),
self.selectedItem = ko.computed(function () {
    var tempreview = self.test();        
    if (tempreview === "a") {
        return ko.observable("2");
    }
    else
        return ko.observable("3");

}),
self.items = ko.observableArray([new Item(3, "")])
};

var vm = new viewModel();
vm.items([new Item(1, "pencil"),
    new Item(2, "pen"),
    new Item(3, "marker"),
    new Item(4, "crayon")
]);
ko.applyBindings(vm);


<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value:selectedItem"></select>

<div data-bind="text: selectedItem"></div>

Jsfiddle link is : //jsfiddle.net/sajesh1985/c7MCh/2/

Thanks, Sajesh

1
  • Please don't just provide your code in a fiddle always include the relevant parts in your question! Commented Mar 12, 2014 at 12:18

1 Answer 1

1

In your selectedItem computed, just return '2' or '3', not an observable:

self.selectedItem = ko.computed(function () {
    var tempreview = self.test();        
    if (tempreview === "a") {
        return '2';
    }
    else
        return '3'

}),
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.