5

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!

Linksonder
  • 732
  • 2
  • 8
  • 17

1 Answers1

2

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);
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
John Rood
  • 805
  • 3
  • 13
  • 25
  • 1
    Thank you for your working solution! I am not able to execute any javascript after the binding element due to the chosen architecture. But i will try to use the afterRender binding to insert the selected options. If i get it to work, i will post the updated solution. – Linksonder Apr 02 '14 at 15:33