Pregunta

I am using optionsValue and value in my knockout databind. However, what I really want is that if I want to preselect an item, I should be (atleast I presume) able to populate the variable assigned to value and it should give me a preselected item. However, it appears undefined at the start. Clearly I am misunderstanding something. What is it that I am doing wrong.

<select data-bind="options: lookupgender, optionsText: 'description', optionsValue: 'code', value: choice,optionsCaption: '-Gender-'"></select>

The whole code is in this fiddle and I expected this to select "female".

¿Fue útil?

Solución

Switch this:

this.choice = choices[1];

To this:

this.choice = ko.observable(choices[1].code);

Or even just this:

this.choice = ko.observable('F');

There were two problems:

  • The choice was not an observable, that means a binding can't be formed between the underlying value and the selected option.
  • The initial value of choice was a whole object { code: 'F', description: "Female" }. But you specified code as optionsValue, so choice should have either value 'F' or 'M'.

Otros consejos

You need to change your syntax slightly:

function ViewModel(choices) {
   this.lookupgender = ko.observableArray(choices);
   this.choice = ko.observable(choices[1].code); 
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top