简体   繁体   中英

Knockout dropdown select list binding array of name/value pairs to observablearray

jsFiddle Demo

I was messing around learning Knockout and I had an issue dealing with the dropdown bindings. Basically it is a mockup of a patient that can have 1 or more diagnosis codes attached.

If you look at my jsfiddle, I have an object with name/value pairs (axis1items) that holds the select list items. I also have an observablearray holding all the results (patientDiags) which is then serialized into JSON.

When you select an item, the value is set as the axis1items item and it is serialized as:

"DiagnosisID":{"dxname":"(V71.81) Abuse and neglect","dxvalue":549}

I would like the final serialized result to be only the dxvalue:

"DiagnosisID": 549

I assume this can easily be done using a computed value, changing the structure of my viewmodels, or some other knockout specific template keyword that I am overlooking ?

In addition: any other suggestions on how to improve my code would be greatly appreciated!

You are almost there, you just need to set the optionsValue to your 'dxvalue' property, where the optionsValue parameter

Similar to optionsText , you can also pass an additional parameter called optionsValue to specify which of the objects' properties should be used to set the value attribute on the <option> elements that KO generates.

So your options binding should look like:

<select data-bind="options: $root.axis1items, 
                   optionsText: 'dxname', 
                   optionsValue: 'dxvalue', 
                   value: DiagnosisID" class="form-control required">
</select>

Demo JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM