$(document).ready(function() {
var viewModel = function() {
var country = function() {
this.key = ko.observable();
this.cname = ko.observable();
};
var state = function() {
this.countryKey = ko.observable();
this.sname = ko.observable();
};
var countries = ko.observableArray([]);
var states = ko.observableArray([]);
var load = function() {
// add countries
countries.push(new country().key(1).cname("USA"));
countries.push(new country().key(2).cname("India"));
// add states
states.push(new state().countryKey(1).sname("New Jersey"));
states.push(new state().countryKey(1).sname("New York"));
states.push(new state().countryKey(1).sname("Ohio"));
states.push(new state().countryKey(1).sname("Kentucky"));
states.push(new state().countryKey(2).sname("MP"));
states.push(new state().countryKey(2).sname("UP"));
states.push(new state().countryKey(2).sname("Maharashtra"));
};
// keep track of selected country
var selectedCountry = ko.observable("");
var selectedState = ko.observable("");
var selectedCountryName = ko.computed(function() {
var cntry = selectedCountry();
if (cntry) {
return cntry.cname();
}
return "";
});
var selectedStateName = ko.computed(function() {
var st = selectedState();
if (st) {
return st.sname() + " , ";
}
return "";
});
// change state selection based on country selection
var selectedStates = ko.dependentObservable(function() {
var cntry = selectedCountry();
var cntryKey;
if (cntry) {
cntryKey = cntry.key();
return ko.utils.arrayFilter(states(), function(item) {
return item.countryKey() === cntryKey;
});
}
return [];
});
// public members
return {
countries: countries,
states: states,
load: load,
selectedCountry: selectedCountry,
selectedStates: selectedStates,
selectedCountryName: selectedCountryName,
selectedState: selectedState,
selectedStateName: selectedStateName
};
}();
viewModel.load();
ko.applyBindings(viewModel);
});
<select data-bind="options:countries, optionsText : 'cname', value:selectedCountry, optionsCaption:'Select...'"></select>
<select data-bind="options:selectedStates, optionsText : 'sname', value:selectedState, optionsCaption:'Select...'"></select> <br/><br/>
<span data-bind="text:selectedStateName"></span><span data-bind="text:selectedCountryName"></span>
External resources loaded into this fiddle: