简体   繁体   中英

'Value' binding doesn't work with optgroup in Knockout

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM