Reputation: 689
I have two select lists, one select list is populated by the selection of the other select list. I have subscribed to the value of the first select box to update the second list every time the value changes. What I am failing to discover is how to reset the second list if a user were to select the default "select ..." option in the first list.
To be clear, the process works, except when a user selects the default options. The Second list keeps the previous selection at that point.
Here's my code (this is an MVC 4 application).
ViewModel:
var DashboardReportViewModel = function (config, originalData) {
var self = this;
self.breweryCode = ko.observable();
self.lineCode = ko.observable();
self.GetBreweries = ko.observableArray([]);
self.GetLines = ko.observableArray([]);
var loadBreweries = function () {
$.ajax({
url: config.GetBreweries,
type: "GET",
error: function (xhr, status, error) {
alert('loadBreweries error');
},
success: function (data) {
self.GetBreweries(data);
},
cache: false
});
};
var loadLines = function () {
$.ajax({
url: config.GetLines,
data: { breweryCode: self.breweryCode() },
cache: false,
type: "GET",
error: function (xhr, status, error) {
alert('loadLines error');
},
success: function (data) {
self.GetLines(data);
}
});
}
loadBreweries();
self.breweryCode.subscribe(function () {
if (self.breweryCode() != undefined) {
loadLines();
}
});
};
View:
<select class="ui-select" id="BrewerySelect" name="BrewerySelect" data-bind="options: GetBreweries,
optionsText: 'Text',
optionsValue: 'Value',
value: breweryCode,
optionsCaption: 'Select a Brewery'"></select>
<select class="ui-select" id="LineSelect" name="LineSelect" data-bind="options: GetLines,
optionsText: 'Text',
optionsValue: 'Value',
value: lineCode,
optionsCaption: 'Select a Line'"></select>
Upvotes: 1
Views: 94
Reputation: 63830
I would go this way:
self.breweryCode.subscribe(function () {
if (!!self.breweryCode()) {
loadLines();
} else {
self.GetLines([]);
}
});
If self.breweryCode()
is truthy an Ajax call will be placed to load the lines, otherwise that list is just emptied completely.
PS. If you like you could also use observableArray
utility methods to do self.GetLines.removeAll()
.
Upvotes: 2
Reputation: 221
You missing else case here:
self.breweryCode.subscribe(function () {
if (self.breweryCode() != undefined) {
loadLines();
}
else {
self.GetLines([]);
}
});
Upvotes: 1