KnockoutJS - Binding value of select with optgroup and javascript objects
http://stackoverflow.com/questions/11189660/knockoutjs-binding-value-of-select-with-optgroup-and-javascript-objects
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="http://mbest.github.io/knockout-repeat/knockout-repeat.js"></script>
<h2>Multiple selected options</h2>
<select data-bind="selectedOptions: selectedOptions" multiple="multiple">
<option>Please choose an option</option>
<optgroup data-bind="repeat: groups" data-repeat-bind="attr: {label: $item().label}">
<option data-bind="repeat: $item().children" data-repeat-bind="text: $item().label, option: $item()"></option>
</optgroup>
</select>
<br>Value:
<div data-bind="foreach: selectedOptions">
<label data-bind="text: label"/>
</div>should be preselected
<br>
<br>
<h3>One selected option</h3>
<select data-bind="value: selectedOption" multiple="multiple">
<option>Please choose an option</option>
<optgroup data-bind="repeat: groups" data-repeat-bind="attr: {label: $item().label}">
<option data-bind="repeat: $item().children" data-repeat-bind="text: $item().label, option: $item()"></option>
</optgroup>
</select>
</br>Value:
<label data-bind="text: selectedOption.label">
<span data-bind="text: label"/>
</label>should be preselected
JavaScript
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.selectExtensions.writeValue(element, value);
}
};
function Group(label, children) {
this.label = ko.observable(label);
this.children = ko.observableArray(children);
}
function Option(label, property) {
this.label = ko.observable(label);
this.someOtherProperty = ko.observable(property);
}
var ViewModel = function() {
this.groups = ko.observableArray([
new Group("Group 1", [
new Option("Option 1", "A"),
new Option("Option 2", "B"),
new Option("Option 3", "C")
]),
new Group("Group 2", [
new Option("Option 4", "D"),
new Option("Option 5", "E"),
new Option("Option 6", "F")
])
]);
//The multiple selected options
this.selectedOptions = ko.observableArray([]);
//The single selected option
this.selectedOption = ko.observable(selected1);
};
var vm = new ViewModel()
ko.applyBindings(vm);
var selected1 = vm.groups()[1].children()[1];
var selected2 = vm.groups()[1].children()[0];
vm.selectedOptions.push(selected1);
vm.selectedOptions.push(selected2);