Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 917
Daniël Tulp Avatar asked May 02 '12 09:05

Daniël Tulp


People also ask

What is two-way data binding in knockout JS?

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.

How do I assign a value to knockout observable?

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.

What is $data in knockout?

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.

What is $root in knockout?

$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.


1 Answers

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>
like image 198
RP Niemeyer Avatar answered Sep 19 '22 14:09

RP Niemeyer