I want Knockout to call an event whenever the user clicks an option in a SELECT element.
Here\'s my JavaScript:
function ReservationsViewModel() {
t
The "alert" should be embedded in a function:
<select data-bind="foreach: availableMeals, event: {change: function () { alert('hello'); } }">
<option data-bind="text: mealName " />
</select>
You should use change
binding instead of click
and optionsText
binding instead of option
tag and use function
in change
binding instead of just calling alert
:
<select data-bind="options: availableMeals, optionsText: 'mealName', value: selectedMeal, event: {change: onChange}">
</select>
function Meal(name, price){
var self = this;
self.mealName = name;
self.price = price;
}
function ReservationsViewModel() {
var self = this;
self.availableMeals = ko.observableArray(
[new Meal("Standard (sandwich)", 0),
new Meal("Premium (lobster)", 34.95),
new Meal("Ultimate (whole zebra)", 290)]);
self.selectedMeal = ko.observable(self.availableMeals()[0]);
self.onChange = function() {
alert("Hello");
};
}
ko.applyBindings(new ReservationsViewModel());
Here is working example: http://jsfiddle.net/Q8QLX/