Reputation: 23
I have a json object that has sites and clients for the sites. One site can have many clients.
I know how to populate the site drop down list box (parent) using knockout bindings. However, I cannot figure out how to populate the clients drop down list (child) when the onchange happens in the parent drop down list.
I would appreciate if someone with more experience could change my code below to show me how to achieve the master/child drop down list functionality.
Cheers
C
var posterArray = ([
{ SiteId: 1,
SiteName: "Mail",
ClientSite:[
{ ClientId: 1, ClientName: "Mail Client A" }, { ClientId: 1, ClientName: "Mail Client B"}]
},
{ SiteId: 2,
SiteName: "DSAC",
ClientSite:
{ ClientId: 1, ClientName: "DSAC Client A" }
}
]);
var ViewModel = function () {
var self = this;
// Poster
self.PosterList = ko.mapping.fromJS([]);
self.PosterListEnable = false;
self.refreshPosterList = function () {
var data = [];
if (posterArray.length == 0) {
data = [{ SiteId: 'No Posters', SiteName: 'No Posters'}];
} else if (posterArray.length == 1) {
data = posterArray;
} else {
data = [{ SiteId: 'Select a Poster', SiteName: 'Select a Poster'}];
data.push.apply(data, posterArray);
}
ko.mapping.fromJS(data, null, self.PosterList);
self.refreshClientList();
};
//Client
self.ClientList = ko.mapping.fromJS([]);
self.refreshClientList = function () {
};
};
var viewModel = new ViewModel();
$(function () {
ko.applyBindings(viewModel);
viewModel.refreshPosterList();
});
</script>
<fieldset class="SearchFilter">
<legend>Search Filter</legend>
<div class="SearchItem">
<span>Poster:</span>
<select id="dllPoster" data-bind="foreach: PosterList, disable:PosterList().length <= 1" onchange="viewModel.refreshClientList();">
<option data-bind="text: SiteName, attr:{value:SiteId}"></option>
</select>
<select id="ddlClient" data-bind="with: PosterList.ClientSite ">
<option data-bind="text: ClientName, attr:{value:ClientId}"></option>
</select>
</div>
</fieldset>
Upvotes: 0
Views: 3293
Reputation: 3570
Knockout has a specific binding for drop down lists. Take look at the "options" binding: http://knockoutjs.com/documentation/options-binding.html
Here's a jsFiddle of your example: http://jsfiddle.net/9QVw9/
Upvotes: 1