I have a knockout foreach binding that generates multiple dropdowns, both single select and multi select. I don't know upfront how much dropdowns there are going to be.
All dropdowns are populated of items of the same datatype but filtered, however I want to gather all selected items from all dropdowns in one observableArray. Binding the same observableArray to all dropdowns in the foreach loop doesn't work as it gets added to the observableArray and immediately deleted by the other dropdown(s).
<script id="multiselect" type="text/html">
<select class="multi-select" multiple="multiple" data-bind="options: Items, optionsText: 'Name', optionsValue: 'Guid', selectedOptions: $root.selectedItems"></select>
</script>
<script id="singleselect" type="text/html">
<select class="single-select" data-bind="options: Items, value: $root.selectedItems"></select>
</script>
<div class="separator">
<!-- ko foreach: distinctItemTypes -->
<label data-bind="text: ItemType.Name"></label>
<div>
<!-- ko template: { name: Count > 1 ? 'multiselect' : 'singleselect' } --><!-- /ko -->
</div>
<!-- /ko -->
</div>
Is this possible or what is the best way to achieve this?
Have each
selectbind to a differentobservableArrayfor its selected values contained within the item you're currently looping over, then add a computed observable at the root level to bring them all together: