How to make a select element with different values then text using Knockout.JS

knockout.js, select

Solution

You would want to map your array `['France', 'Germany', 'Spain']` to a structure that would have separate properties for `value` and `text`.

For example,

[
   { value: 1, name: 'France' }, 
   { value: 2, name: 'Germany' }, 
   { value: 3, name: 'Spain' }
]

Then, you can bind against it like:

<select data-bind="options: availableCountries, optionsText: 'name', optionsValue: 'value'"></select>

Problem

I understand that ``` <p>Destination country: <select data-bind="options: availableCountries"></select></p> <script type="text/javascript"> var viewModel = { availableCountries : ko.observableArray(['France', 'Germany', 'Spain']) // These are the initial options }; ko.applyBindings(viewModel); </script> ``` will create a select element like: ``` <select data-bind="options: availableCountries"> <option value="France">France</option> <option value="Germany">Germany</option> <option value="Spain">Spain</option> </select> ``` but what if I want it to be like: ``` <select data-bind="options: availableCountries"> <option value="1">France</option> <option value="2">Germany</option> <option value="3">Spain</option> </select> ``` what would be my code? I know I can use optionsText to fill the options, but optionsValue doesn't seem to work for me cheers, Daniël

Original source