Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout multiple select selectedOptions not selected on load

Tags:

knockout.js

I'm creating an edit form for a user, the roles of the user are not selected by default in a multiple select.

There are 2 application roles: "Administrator" and "Moderator". The sample user has 1 role "Administrator". This one is not selected by default.

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 an dependentObservable and mapped that one 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/

like image 417
Bas Avatar asked Nov 22 '12 17:11

Bas


Video Answer


2 Answers

The problem is that Roles contains "full" object whereas it should contain only the value part:

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

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

like image 59
Tomasz Zieliński Avatar answered Sep 22 '22 16:09

Tomasz Zieliński


Knockout needs to compare selected options by values, which is Id in this case: optionsValue: 'Id'. And you're passing an array of Role objects. You need to pass array of Id instead:

var User = function () {
    ...
    self.Roles = ko.observableArray([1]);
};
like image 28
Max Shmelev Avatar answered Sep 18 '22 16:09

Max Shmelev