Reputation: 89
I am binding an object to a dropdownlist using Knockout 2.2.1. The binding is working for putting the correct items in the list but when I try to get the OBJECT selected it is not working. I have a JSFiddle showing this problem; http://jsfiddle.net/CTBSTerry/g4Gex/
Html
<div style="margin-bottom: 15px;">
Your Choices:
<select data-bind="options: choicelists[0].options, optionsText: 'otext', optionsValue: 'oprice', value: selOpt1, optionsCaption: 'Choose...'"></select>
</div>
<div data-bind="visible: selOpt1" style="margin-bottom: 15px;"> <!-- Appears when you select something -->
You have chosen<br>
From Object:
<span data-bind="text: selOpt1() ? selOpt1().otext : 'unknown'"></span>
<br>From Value:
<span data-bind="text: selOpt1() ? selOpt1() : 'unknown'"></span>
</div>
JavaScript:
var mychoice = function (txt, price) {
this.otext = txt;
this.oprice = price;
}
var viewModel = {
prodphoto: "",
prodname: "",
prodDesc: "",
baseprice: "",
choicelists: [
{ 'listlabel': 'Size List',
'options': ko.observableArray([
new mychoice('Small', 'Small|$|0.00'),
new mychoice('Medium', 'Medium|$|0.00'),
new mychoice('Large', 'Large|$|0.00'),
new mychoice('X Large + 2.00', 'X Large|$|2.00'),
])
}],
textlists: [],
selOpt1: ko.observable()
}
ko.applyBindings(viewModel);
When you click the dropdown to make a choice I have 2 spans that attempt to show the selected value which I want as the object selected not just the specific value field. The object notation returns nothing but does not error. The second span shows the selected value but since it is not the selected object I would have to iterate through the object to get the related object. The Knockout documentation shows a very similar sample but I need a bit more complex view model. Can someone help me and point out why this is not working?
Thanks, Terry
Upvotes: 1
Views: 453
Reputation: 114792
If you remove optionsValue
from your binding, then Knockout will use the actual object rather than a property on it.
So, you would want to remove optionsValue: 'oprice'
from the binding, then selOpt1
will be populated with the actual object.
Sample: http://jsfiddle.net/rniemeyer/g4Gex/1/
Upvotes: 1