0
votes

I'm having difficulty getting a chosen multi-select field to populate when setting the selected options and then updating the field.

In my application I'm using knockout.js to bind observables/observableArrays to my fields and in the chosen field the options are a list of objects. Based on the options selected in this field, I want to populate a separate drop down with the objects previously selected.

Everything works fine when I'm starting without any pre-selected options, however when I populate the selected options knockout observableArray using JavaScript and then call the chosen update command, the chosen field remains empty but the separate drop down is successfully updated.

Html:

<label>User(s):</label>
<select class="chosen form-control" multiple data-bind="options: userOptions, selectedOptions: selectedUsers,
            optionsText: function (user){ return user.name}"></select>
<label>Primary User:</label>
<select class="form-control" data-bind="options: selectedUsers, optionsText: 'name', value: primaryUser></select>

Knockout Variables:

vs.userOptions: ko.observableArray([]);
vs.selectedUsers: ko.observableArray([]);
vs.primaryUser: ko.observable();

userOptions/selectedUsers Object:

{
id: -1,
email: "",
name: ""
}

JavaScript:

vs.selectedUsers.removeAll();
$.ajax({
    url: url,
    type: "GET",
    success: function (data) {
        for (var i = 0; i < data.length; i++) {                
            var object = {
                id: data[i].id,
                email: data[i].email,
                name: data[i].name
            };
            vs.selectedUsers.push(object);
            if (data[i].primaryUser) {
                vs.primaryUser(object);
            }
        }
        $(".chosen").trigger("chosen:updated");
    },
    error: function (xhr, status, error) {
        //Handle error...
    }
});

**Note: data from Ajax GET call returns an array of objects containing pkey, id, email, name, and primaryUser, where primaryUser is a boolean value identifying whether or not they were the primaryUser selected

1

1 Answers

0
votes

Update: came back to the problem and found a fix that worked. I had to adjust the code within the ajax success function:

vs.selectedUsers.removeAll();
$.ajax({
    url: url,
    type: "GET",
    success: function (data) {
        for (var i = 0; i < data.length; i++) {
            for (var j = 0; j < vs.userOptions().length; j++) {
                if (vs.userOptions()[j].id === data[i].id) {
                    vs.selectedUsers.push(vs.userOptions()[j]);
                    if (data[i].primaryUser) {
                        vs.primaryUser(vs.userOptions()[j]);
                    }
                    break;
                }
            }
        }
        $(".chosen").trigger("chosen:updated");
    },
    error: function (xhr, status, error) {
        //Handle error...
    }
});