Imran Rashid
Imran Rashid

Reputation: 3492

Select2 with knockout how to show selected items in select?

I have select2 control with multiple select for displaying User's roles and I am getting selectedRoles collection from server while select2 requires only selected item's id only not the whole collection.

<select multiple="multiple" 
 data-bind="options: AllRoles, optionsValue: 'Id', optionsText: 'Name', selectedOptions: selectedRole, select2: {}"></select>

I have selected Roles as collection in observableArray but select2 requires collection of string to show selected items.

 AllRoles = ko.observableArray([{Id: '111', Name: 'Test'}, {Id: '2222', Name: 'TTTTT'}]);
 selectedRole = ko.observableArray(["111","2222"]);
 ??? selectedRoles = ko.observableArray([{Id: '111', Name: 'Test'}, {Id: '2222', Name: 'TTTTT'}]);

What is best way to resolve this issue should i have separate string array or i can do this with existing collection?

Here is example fiddle

Upvotes: 1

Views: 5197

Answers (1)

Svend
Svend

Reputation: 8158

I'm assuming the problem is that you have a object array from the server, and want to use this as a source for what elements are preselected in the lower dropdown of your fiddle?

If so, the problem is that when you set the selectedOptions: selectedRoles, Knockout will overwrite this as it cannot infer selected items from the list containing objects, when the selected values are strings. You can make a computed variable however that adapts the selectedRoles array however. The binding selectedOptions can use this just fine.

self.selectedRolesComp = ko.computed(function() {
    var l = [];
    for(var i = 0; i < self.selectedRoles().length; i++) {
        l.push(self.selectedRoles()[i].Id);
    }
    return l;
});

As a fiddle http://jsfiddle.net/WGukF/2/

Take a further look at http://knockoutjs.com/documentation/computedObservables.html for more.

Upvotes: 1

Related Questions