Select multiple knocked selected items not selected at boot time

I am creating an editing form for a user; user roles are not selected by default with multiple selections.

There are two roles for the application: Administrator and Moderator. The user of the sample has 1 role "Administrator". By default, this check box is not selected.

http://jsfiddle.net/jgT8s/4/

HTML:

<form data-bind="with: user"> <select id="selectRoles" data-bind="options: $root.allRoles, selectedOptions: Roles, optionsText: 'Name', optionsValue: 'Id'" multiple="true" size="5"> </select> </form> 

JS:

 var User = function () { var self = this; self.Id = ko.observable(1337); self.Username = ko.observable('pietpaulusma'); self.Roles = ko.observableArray([{ Id: 1, Name: 'Administrator' }]); }; function UserViewModel() { var self = this; self.user = ko.observable(new User()); self.allRoles = ko.observableArray([{ Id: 1, Name: 'Administrator' }, { Id: 2, Name: 'Moderator' }]); } ko.applyBindings(new UserViewModel()); 

UPDATE created a dependentOnable and mapped it to selectedOptions

 self.RoleIds = ko.dependentObservable(function () { return ko.utils.arrayMap(self.Roles(), function (role) { return role.Id; }); }); 

working version: http://jsfiddle.net/jgT8s/5/

+6
source share
2 answers

The problem is that Roles contains a โ€œfullโ€ object, while it should only contain a part of the value:

 self.Roles = ko.observableArray([1]); 

Take a look here: http://jsfiddle.net/Vkda5/

+6
source

The knockout needs to compare the selected parameters by the values, which in this case are Id : optionsValue: 'Id' . And you pass an array of Role objects. You need to pass an Id array instead:

 var User = function () { ... self.Roles = ko.observableArray([1]); }; 
+3
source

All Articles