2013-11-01 69 views
1

这里的小提琴:KnockoutJS选择下拉无法用所选值预先填充

http://jsfiddle.net/adNuR/2187/

// Template 
<div data-bind="foreach: lines"> 
    <p data-bind="text: item.description"></p> 
    <select data-bind="value: item, options: sampleOptions, optionsText: 'description', optionsCaption: 'Please select'"></select> 
</div> 


// JS 
var sampleOptions = [ 
     { description: "item 1" }, 
     { description: "item 2" }, 
     { description: "item 3" }, 
     { description: "item 4" } 
     ];  

var Model = function() { 
    var self = this; 
    self.lines = ko.observableArray([ 
     { item: { description: "item 1" } }, 
     { item: { description: "item 2" } } 
    ]); 
}; 

ko.applyBindings(new Model()); 

基本上我有绑定到一个选择框的对象,但它不是选择在下拉列表中选择的选项。它会显示正确的值,如果我将选定的选项的文本数据绑定到另一个元素,但我似乎无法得到选择框加载与初始预选值无论我尝试。

也许有些琐碎和愚蠢,但我似乎无法弄清楚它......任何帮助表示赞赏。

回答

1

你的问题可能是这个副本:Select element's initial value

所以基本上你需要比较两个字符串,看看哪些价值应该首先在下拉菜单中进行设置。它看起来不适用于整个对象。要快速解决您的例子是这个(更新小提琴:http://jsfiddle.net/adNuR/2189/):

<select data-bind="value:item.description, options: sampleOptions, optionsValue:'description', optionsText: 'description', optionsCaption: 'Please select'"></select> 

但你可能会想一些适当的ID添加到对选择和比较基于这些。

+0

是的,真正的代码要复杂得多,并且保存动态生成的对象,并在其中嵌入列表,以表示稍后在表单中的其他选择框的可能值,所以我确实需要保存整个对象而不仅仅是一个文字。事实证明,由于你提到的原因,它不会很好地工作,所以我现在只是重新修改它而完全不同,而且看起来没问题。将接受这个答案,因为它确实解决了小提琴中概述的具体问题:)谢谢! – ARW

相关问题