I finally got optgroups to work with Knockout using this:
<select data-bind="foreach: $root.countries, value: selectedCountry">
<optgroup data-bind="attr: {label: label}, foreach: children">
<option data-bind="text: label"></option>
</optgroup>
</select>
This shows a list of all countries grouped by continent. But, I can’t get the selectedCountry to work. What am I missing here?
For the record: selectedCountry is a property of ‘user’ (the country the user lives in). I loop over all users using this:
<tbody class="sortable user_div" data-bind="sortable: { data: form.users }">
<!-- Here a <tr> and all form elements, including the <select> above -->
</tbody>
This works within the same tbody the select is in:
<td><input type="text" data-bind="value: userName" /></td>
I’m accessing both userName and selectedCountry in the same way (as you can see). Both are properties of the User object. I’m 100% positive selectedCountry is the right property. When I switch userName and selectedCountry, I get the selectedCountry in the <input type="text">.
Ooooooh, I’m so stupid.
<option data-bind="text: label"></option><– there I’m not binding any value. So this was the solution:<option data-bind="text: label, value: label"></option>