john Smith
john Smith

Reputation: 17926

Knockout options binding reference property

I´m having an observableArray, that gets populated by an ajax call and looking like

appModel.foo().bar().fooBarCategories()
[
Object:
  id: Object
     type: "integer"
     value: "4986517"
  name: "Adwords"
, 
Object
, 
Object,
...
]

and I´m having a select where I want the optionsText to be "name" property and the value "id.value" property

like:

<select id="fooBarCategory" 
  data-bind="
      options: appModel.foo().bar().fooBarCategories(), 
      optionsText: name, 
      value: id.value"
></select>

but it doesn't work saying:

Uncaught ReferenceError: Unable to process binding "value: function (){return id.value }" Message: id is not defined

so how would can I achieve that? tried stuff like value:$data.id.value or

value:this.id.value

this is how I got it to work with the name property:

optionsText:function(item) {
    return item.name
}

but if do similiar with the id property

value:function(item){ return item.id.value }

then the value attr in the generated options keeps blank

here you have a fiddle http://jsfiddle.net/q65nz/1/

Upvotes: 2

Views: 65

Answers (1)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

Well i will suggest do it like this create a function because it is an object so wont take the usuall form.

self.setValue = function (item) {
    return item.id.value
}

And now call it like this

<select data-bind="
    options: appModel.foo().bar().fooBarCategories(), 
    optionsText: 'name',
    optionsValue : setValue
">
</select>

Fiddle Demo

Fiddle Demo with Your Provided Data

You should use optionsValue binding instead of value binding

Upvotes: 2

Related Questions