Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS Select Options and Selected Value

Tags:

knockout.js

Similar question as: Select element's initial value

I'm having an issue setting the initial value of the select element. I basically have a list of seed data coming in from the server to populate the drop down list, and I want the selected value to represent what should be selected from the entity.

Because the data model's selected value doesn't equal the object reference in the seed data, nothing is selected.

Right now, I'm looping through each entity, finding the correct selected value, setting that equal to the seed data's equivalent, then Knockout knows how to wire it up.

Is there a more elegant solution that this? I fiddled a simplified example with more details... http://jsfiddle.net/hbrYM/14/

like image 606
aswallows Avatar asked May 10 '12 22:05

aswallows


People also ask

What is $data in Knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is applyBindings in Knockout?

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .

What is Ko observable in knockout JS?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.


1 Answers

As you correctly guessed the selectedValue reference doesn't match so KO doesn't select that item. The way to get this to work is to not save the complex object in the selected value and instead select the ID, as a primitive type equality can succeed and the correct value is selected.

http://jsfiddle.net/VLTFB/3/

You'll need to use the optionsValue option on the options binding (if that makes sense :)

<select data-bind="options: seedData,
                    optionsText: 'firstName',
                    optionsValue: 'ID',
                    value: data.selectedValue">

EDIT

As discussed you can reselect the correct item with a computed (untested).

vm.currentlySelected = ko.computed(function () { 
   for (var i = 0; i < this.seedData().length; i += 1) {
       var data = this.seedData()[i];
       if (data.ID === this.selectedValue()) {
           return data;
       }
   }
   return null;
}, vm);

Hope this helps.

like image 139
madcapnmckay Avatar answered Oct 05 '22 21:10

madcapnmckay