Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preselect multiple values using the selectedOptions knockout binding in an select with optgroup

Ello,

I've litteraly tried all the options to making a (multiple) selectbox with optgropus, and binding the options/selectedOptions with knockout.

There seems to be an issue with the selectedOptions binding. My data seems to be legit, but it just won't show the preselected options.

I've made an example in JSFiddle: http://jsfiddle.net/aCS7D/251/

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

With a single selected option it works, but with multiple selectedoptions, the selectbox does not render them correctly.

If any one has a solution to this problem you would be my hero!

like image 222
Linksonder Avatar asked Nov 02 '22 02:11

Linksonder


1 Answers

You can push them after you apply bindings like this:

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);
like image 117
John Avatar answered Nov 09 '22 14:11

John