haki
haki

Reputation: 9759

Return selectvalue as object from a bound option list in Knockout

I want to bind a key value object to an optionlist in knockout

function ParameterOption(name , value) { 
    this.name = name;
    this.value = value;
}

My select list

<select data-bind="
  options: Options, 
  value: SelectedValue,
  optionsText: 'name',
  attr :{'id':Id, 'name':Name}"></select>

I'm using cascading dropboxed so I need the option text to fetch the next list. When I submit the form I want to send the value.

This is a working fiddle of what i've done so far.

My problem is that if i dont set optionsValue when i submit the form the parameters has no value. but, if i set optionsValue : 'value' i get the raw value in the model and not a ParameterOption object as i should.

Is there a way of binding the value to the option and still retrive an object as the selected value back to the model ?

Upvotes: 0

Views: 67

Answers (1)

Michael Best
Michael Best

Reputation: 16688

You can use the optionsAfterRender parameter to set the value property of each option, giving the select box a text value when submitting, but not upsetting the object value used by Knockout:

optionsAfterRender: function(option, item) { option.value = item.value }

jsFiddle: http://jsfiddle.net/7fJkh/4/

Reference: http://knockoutjs.com/documentation/options-binding.html

Upvotes: 1

Related Questions