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