简体   繁体   中英

Retrieving value from select list with knockout.js

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM