I want Knockout to call an event whenever the user clicks an option in a SELECT element.
Here's my JavaScript:
function ReservationsViewModel() {
this.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
}
ko.applyBindings(new ReservationsViewModel());
Here's my HTML:
<select data-bind="foreach: availableMeals">
<option data-bind="text: mealName, click: alert('hello')" />
</select>
But when I run this, the application shows "hello" three times even though none of the options were actually clicked.
What am I doing wrong?
The "alert" should be embedded in a function:
You should use
change
binding instead ofclick
andoptionsText
binding instead ofoption
tag and usefunction
inchange
binding instead of just callingalert
:Here is working example: http://jsfiddle.net/Q8QLX/