1

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:&nbsp;
    <span data-bind="text: selOpt1() ? selOpt1().otext : 'unknown'"></span>
    <br>From Value:&nbsp;
    <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

1 Answer 1

1

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/

1
  • This worked perfectly - thanks! I thought I had followed the example exactly but got two examples confused and spent a couple hours spinning my wheels. This answer is very much appreciated and now I can get back to implementing the whole solution. I am a newbie to knockout so I am wandering around a bit.
    – Terry H
    Commented May 30, 2013 at 12:52

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.