I use knockoutjs and have two dropdowns. One of them depends on the other. This alone works fine, but now I want to set the initial values โโand their selected value.
Since I subscribe to a change in the first drop-down list to download the second drop-down list, I not only download the data twice, but also lose my original choice in the second drop-down list. The reason for this is because I have to clear the selection of the second drop-down list when the first changes its values. Otherwise, the wrong value may be selected.
See: http://jsfiddle.net/sturm/6Mp33/31/
<select name="model" data-bind="options: models, value: selectedModel, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'"></select> <select name="makes" data-bind="options: makes, value: selectedMake, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Choose...'"></select> function viewModel(initialModels, initialSelectedModel, initialMakes, initialSelectedMake) { var self = this; self.models = ko.observableArray(initialModels); self.selectedModel = ko.observable(initialSelectedModel); self.makes = ko.observableArray(initialMakes); self.selectedMake = ko.observable(initialSelectedMake); self.selectedModel.subscribe(function() { // This runs after the initial data and clears the selection if (self.selectedModel()) { $.ajax({ type: 'POST', url: '/echo/json/', data: { json: ko.toJSON(makeData[self.selectedModel()-1]) }, context: this, success: function(data) { self.makes(data); // The folowing line is the problem self.selectedMake(undefined); }, dataType: 'json' }); } else { self.makes.removeAll(); } }); }; ko.applyBindings(new viewModel(modelData, 2, makeData[1], 2));
How can you clean the initial values โโwithout double loading and saving the selection?
source share