I am trying to use a nested options, (optionsText, optionsValue) and value binding inside a foreach binding in KO.
I expected the following code to bind the select box to the ViewModel’s related Item but it doesn’t appear to be updating the values in the view model – they always stay as the value I initialised them with “n/a” – how can I do that?
I have set up a html page as follows:
<table>
<tbody data-bind="foreach: Items">
<tr>
<td>
<select data-bind="options: $parent.Countries, optionsText: 'Name', optionsValue: 'Code', value: 'Country'"></select>
</td>
<td>
<span data-bind="text: Country"></span>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<a href="#" data-bind="click: AddItem">Add item</a>
</td>
</tr>
</tfoot>
</table>
With the following JavaScript:
var countries = ko.observableArray([
{ Name : "United Kingdom", Code : "UK", Population : "1 Monarch" },
{ Name : "Australia", Code : "AU", Population : "22 million kangaroos" },
{ Name : "Antarctica", Code : "AQ", Population : "100,000 penguins (0 polar bears)" }
]);
var item = { Country : "n/a" };
var ViewModel = function() {
this.Countries = countries;
this.Items = ko.observableArray();
this.AddItem = function() {
this.Items.push(ko.mapping.fromJS(item));
};
};
var vm = new ViewModel();
ko.applyBindings(vm);
The fiddle is here
Remove quotes from
valuebinding:Here is working fiddle:
link