knockout-select2
knockout-select2 copied to clipboard
selectedOptions value cleared on first option selection
I have a multiselect as such:
<select multiple="multiple" data-bind="options: programMakes(), selectedOptions: makes, optionsText: 'name', select2: {}" style="width: 100%;"></select>
And I have data that looks like this:
makes = ko.observableArray([{ id: 1, name: 'test1'}]);
programMakes = ko.observableArray([{ id: 1, name: 'test1'}, { id: 2, name: 'test2'}]);
The select properly initializes with the selectedOptions; however, as soon as I add test2 to the selectedOptions (i.e. makes), test1 is removed and only test2 exists in makes. It appears that select2's val() is not being correctly initialized (checking the select input's value in console shows it initializes as null).
Any suggestions?
This seems to be setup very close to my multiselect example in the labs. Could you verify if this occurs with the lab code. I am not in a position to test myself at the moment.
So your labs seem to working as I would expect. It's looking like I don't have something set up correctly. It appears that if I have a separate array of selected option objects defined, although matching the available options objects, the select widget can't match them up.
Taking this code...
var options = [
{ id: '0', text: 'Red' },
{ id: '1', text: 'White' },
{ id: '2', text: 'Blue' }
];
var selectedOptions = ko.observableArray([options[0]]);
var spec = {
tags: true
};
var model = {
spec: spec,
options: options,
selectedOptions: selectedOptions,
optionsText: function(item) {
return item.text || item;
}
};
... and changing it around to (where selectedOptions is now sOptions and I'm defining the object):
var options = ko.observableArray([
{ id: '0', name: 'Red' },
{ id: '1', name: 'White' },
{ id: '2', name: 'Blue' }
]);
var sOptions = ko.observableArray([
{
id: '0',
name: 'Red'
}
]);
var spec = {
tags: true
};
var model = {
spec: spec,
options: options(),
selectedOptions: sOptions,
optionsText: function(item) {
return item.name || item;
}
};```
I get the same results that I was experiencing in my own code.
I guess it's probably using the object reference rather than comparing the objects. Is there a way to have it compare values, such as 'id', instead?
Have you tried specifying options value?