OK I am trying to get my head around knockoutjs nested dropdowns.
Basically I want to select an option from a binded dropdown a, and have dropdown b display the related options.
Here is the model which i have pinched from the knockout tutorial and amended:
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
var self = this;
// Non-editable catalog data - would come from the server
self.availableMeals = ko.observableArray([
{ mealName: "Standard (sandwich)", price: 0, Sizes: [{ Desc: "large" }, { Desc: "medium" }, { Desc: "small" }] },
{ mealName: "Premium (lobster)", price: 34.95, Sizes: [{ Desc: "large1" }, { Desc: "medium1" }, { Desc: "small1" }] },
{ mealName: "Ultimate (whole zebra)", price: 290, Sizes: [{ Desc: "large2" }, { Desc: "medium2" }, { Desc: "small2" }] }
]);
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[0])
]);
}
ko.applyBindings(new ReservationsViewModel());
Then my html:
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name" /></td>
<td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="with: $root.availableMeals">
<select data-bind='options: $parent.Sizes, optionsText: "Desc", optionsCaption: "Select...", value: Desc'> </select>
</td>
<td data-bind="text: meal().price"></td>
</tr>
</tbody>
Now I know my html is probably not right as I have messed with a lot to try and get this working but basically I want to select a meal from the dropdown and have its relevant sizes display in the 2nd dropdown…
What am I doing wrong?!
Currently, all of the
SeatReservationobjects point to potentially the same copy of theavailableMealitems.If each reservation is able to customize the “size”, then you would likely want to store the size on the reservation object. Maybe like:
Then you can bind like:
Sample here: http://jsfiddle.net/rniemeyer/HsDeG/