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
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With