Karthik Bammidi
Karthik Bammidi

Reputation: 1851

How to bind list of items with in dropdownlist using knockout.js

I am working on knockout.js. I am very new to knockout.js so iam following knockout.js tutorials. I am trying to display list of items with in dropdownlist basically it is actual example provided in knockout.js tutorials. I have written following code,

<script type="text/javascript">
        $(document).ready(function () {
            function setreservation(name, initmeal) {
                var self = this;
                self.Name = name;
                self.Meal = ko.observable(initmeal);

                self.FormatPrice = ko.computed(function () {
                    return self.Meal().Price ? "$" + self.Meal().Price.toFixed(2) : "none";
                });
            }

            function ReservationViewModel() {
                var self = this;
                self.availablemeals = [{ "MealName": "standard", "Price": 10 }, { "MealName": "premium", "Price": 20 }, { "MealName": "Platinum", "Price": 30}];
                self.seats = ko.observableArray([new setreservation("karthik", self.availablemeals[0]), new setreservation("Tirumalesh", self.availablemeals[1])]);
                self.ReserveNewSeat = function () {
                    self.seats.push(new setreservation("karhik", self.availablemeals[2]));
                };
            }

            ko.applyBindings(new ReservationViewModel());
        }); 

and my view is like,

<table cellpadding="3" cellspacing="4">
<thead>
<tr>
<th>Name</th><th>Meal</th><th>Price</th>
</tr>
</thead>
<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="text:FormatPrice"></td>
</tr>
</tbody>
</table>
<button data-bind="click:ReserveNewSeat">Reserve New One</button>

so please guide me does my code makes any thing wrong.

Upvotes: 1

Views: 9488

Answers (1)

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You missed '' in optionsText binding:

<select data-bind="options: $root.availablemeals, value: Meal, optionsText: 'MealName'">

Here is working fiddle: http://jsfiddle.net/vyshniakov/DRDGK/

Upvotes: 3

Related Questions