I'm trying to make a simple knockout.js-page: First the user needs to select a car brand, after that, a model. This works. Now i want additionally the number of doors shown (4 or 5).
But the number of doors (selectedModel().AantalDeuren') are never shown. What is wrong with my code? ps: i've started from http://knockoutjs.com/examples/cartEditor.html Goal is to make a ShoppingCart, with data from mvc-api, which is already working. Thanks, bram
<html>
<head>
<title>KnockoutJS Options Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"; type="text/javascript">
</script>
</head>
<body>
<table>
<tr>
<td>
<select data-bind="options: availableMerken, optionsText: 'MerkNaam', value: selectedMerk, optionsCaption: 'Kies merk..'"></select>
</td>
<td>
<select data-bind='options: selectedMerk().modellen, optionsText: "ModelNaam", value:selectedModel, optionsCaption: "Kies model.."'> </select>
</td>
<td>
<span data-bind='text: selectedModel().AantalDeuren'> </span>
</td>
</tr>
</table>
<script type="text/javascript">
var Model = function (_modelnaam, _aantaldeuren) {
var self = this;
self.ModelNaam = _modelnaam;
self.AantalDeuren = _aantaldeuren;
};
var Merk = function (naam, extra1, extra2) {
var self = this;
self.MerkNaam = naam;
self.modellen = ko.observableArray();
self.modellen.push(new Model(extra1, 4));
self.modellen.push(new Model(extra2, 5));
//this.modellen[0] = new Model(extra1, 4);
//this.modellen[1] = new Model(extra2, 5);
};
function ViewModel() {
var self = this;
self.selectedMerk = ko.observable();
self.selectedModel = ko.observable();
self.availableMerken = ko.observableArray([
new Merk('vw', 'golf', 'polo'),
new Merk('bmw', '3', '5'),
new Merk('audi', 'A4', 'A6'),
new Merk('mercedes', 'C', 'GLE'),
new Merk('ford', 'escort', 'scorpio'),
new Merk('opel', 'astra', 'monza'),
]);
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Did you check the console for errors?
The issue is that initially, both selections are
undefined
. Your data-binds look forundefined.modellen
andundefined.AantalDeuren
, resulting in errors.Fix it by checking if there is a selection, before binding to one of its properties: