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/
source share