2

Maybe I am misunderstand how this works. I want to use knockout.js to populate a select element options. I am using the following markup to achieve this:

<select data-bind="options: type_options, optionsText: function(item) {
            return item.text;
        }, optionsValue: function(item) {
            return item.value;
        }, optionsCaption:'Select a type...',
        value: type">

Here is the relevant model code:

 var myModel = {
    type: ko.observable(),

    type_options: ko.observableArray([
        {text: "String 1", value:1},
        {text: "String 2", value:2},
        {text: "String 3", value: 3},
        {text: "String 4", value: 4},
        {text: "String 5", value: 5}
    ]),
 }

Now the drop down renders correctly, with all the correct text and values, but when I select the an option from the drop down it doesn't set the value of 'type' correctly.

For instance if I selected the option labeled "String 4", and run the following command in the browser:

myModel.type()

I would expect it to return the value "4". Instead i get the object entire object:

Object
     text: "String 4"
     value: 4
     __proto__: Object

My question is how do i get knockout to set the value of type based on the option's value attribute, instead of the entire object?

1 Answer 1

4

Well, you should be able to pass the text for the variable in you options array instead of a function. I don't know if that's what's causing the issue but your markup would look better like

<select data-bind="options: type_options, optionsText: 'text', optionsValue: 'value', optionsCaption:'Select a type...', value: type"></select>

That should get you what you want, see fiddle for full example.

3
  • hi, thank you for your fiddle. I actually am using the json object version of the view model (see my updated code above). I tried changing it to the function form, and found problems left and right, not related to this issue. Do you know how to do this with JSON form of view models?
    – aamiri
    Oct 3, 2012 at 19:51
  • @aamiri I have updated the fiddle to use the object viewModel direction.
    – Rynan
    Oct 3, 2012 at 20:28
  • I don't know why that wasn't working for me, but I rewrote it and it worked. I wish I knew why it wasn't working but thank you for your help.
    – aamiri
    Oct 4, 2012 at 1:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.