Reputation: 67
I'm using Knockout.js 2.3.0 and I'm trying to retrieve a value set in a select list, but I can't get it to work. When I try to alert the value, I either see javascript, undefined or [object object] (depending on what I've tried).
The list is populated fine and I can set the default value, but I can't retrieve it. What am I doing wrong?
Here's the HTML for the list
<select data-bind='value: selectedMonth, options: $root.months, optionsText: "month"'></select>
And here's the JS
self.months = [{month: '-'},{month: '01'},{month: '02'},{month: '03'},{month: '04'},{month: '05'},{month: '06'},{month: '07'},{month: '08'},{month: '09'},{month: '10'},{month: '11'},{month: '12'}];
self.selectedMonth = ko.observable(self.months[0]);
self.submitButton = function(){
alert(self.selectedMonth); //a bunch of JavaScript
alert(self.selectedMonth()); //object, Object
alert(self.months[self.selectedMonth]); //undefined
}
Here is a fiddle with the code
Upvotes: 2
Views: 75
Reputation: 63729
Your second call is the one you want:
self.selectedMonth()
This unwraps the observable to the value. It's an Object, being for example:
{ month: "03" }
This is easier to spot if you console.log
instead of alert
.
In any case, to get the month value just ask for that property:
alert(self.selectedMonth().month);
See this fiddle.
Upvotes: 3