I'm trying to create custom binding in knockout to use it as multiple selection field. For example: I want to design selection screen for invoice report. On this selection screen I would like to use field 'Invoice Type' to allow users to provide only the types of invoices, they are interested in. If I use standard text box for this field, users would be allowed only to provide one invoice type. I want them to be able to provide more than one type in selection. My idea was to prepare a binding such as:
// html
<input data-bind="multiple: { data: optionsArray }" />
...
// view model
optionsArray = ko.observableArray();
where I could provide field 'optionsArray', which would hold the multiple choise of users (in my case that would be multiple invoice types). If it comes to UI, I thought it could look like this: there's a button next to the element with multiple binding. After clicking it, dialog window appears and all the 'optionsArray' elements are displayed there and can be changed, new can be added or deleted.
I don't know how to achieve this because I failed on the part of displaying all the optionsArray elements in dialog box in a way they can be edited as observables and all the changes are reflected in viewModel.optionsArray. Is this even possible?
Do you have any experience in building custom bindings and help me with this?
You don't need to create custom binding
for that. You can use selectedOptions
binding here is link to the documentation: http://knockoutjs.com/documentation/selectedOptions-binding.html.
Add optionsArray
and selectedTypes
observable arrays to your view model:
self.optionsArray = ko.observableArray();
self.selectedTypes = ko.observableArray();
And bind to multiselect
:
<select data-bind="options: optionsArray, selectedOptions: selectedTypes" size="5" multiple="true"></select>
Here is working example with dialog and adding new options: http://jsfiddle.net/vyshniakov/nZtZd/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With