简体   繁体   中英

knockoutjs select data-bind binding is given unexpected result

I am just started to use knockoutjs. I try to bind the select option value with knockout data-bind property.But am not able to get the array values as different options. It will populate as coma separetd. i had attaching the sample code i tryied.I hope some others will also face the same strange error.

self.availableStates = new Array(); 
for (var i=0;i<self.allStates.length;i++)
{
if (self.allStates[i]['name'] != null)
self.availableStates.push(self.allStates[i]['name'])
}
self.availableStates = ko.observableArray([self.availableStates]);

Expecting result:

<select id="drpDwnLst" data-bind="options: availableStates">
    <option value="">State4</option>
    <option value="">State3</option>
    <option value="">State2</option>
    <option value="">State1</option>
</select>

Actual result

<select id="drpDwnLst" data-bind="options: availableStates">
    <option value="">State4,State3,State2,State1</option>
</select>

What you see in the output is the effect of calling toString() on an array.

You get this result because your availableStates is already an array so you don't need to wrap it again to an array with []

So you need to just write:

self.availableStates = ko.observableArray(self.availableStates);

Although it is strange how you override your self.availableStates definition...

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