aswallows
aswallows

Reputation: 320

KnockoutJS Select Options and Selected Value

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/

Upvotes: 19

Views: 44681

Answers (1)

madcapnmckay
madcapnmckay

Reputation: 15984

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.

Upvotes: 35

Related Questions