使用JSON中的选定索引预填充下拉值

时间:2014-04-01 05:17:28

标签: jquery knockout.js

我正在尝试实现一个小功能。我有行文本框和下拉列表,所有值将作为服务器端的数组。我可以将所有数据绑定到客户端,除了下拉列表的选定值(它总是指向下拉列表中的第一个)。请告诉我如何将所选值设置为活动状态,从服务器端填充数据时。

 <select class="ddText" id="selType" data-bind="options:typeDropDown, optionsText: 'Value', optionsValue: 'Value',value : Type,attr: { name: 'age',id : 'str_'+$index()}, uniqueName:true" "></select>

我已尝试在上面的代码中将值添加到值bind中。像这样(值:Type.Value - 从JSON填充时起作用,同时创建带有错误的新行“找不到类型的属性值

Dropdowns and JSON Objects and Binding the selected value

由于我具有创建动态行的功能,因此在创建新行时出现错误。

我是否需要重建我的阵列?

更新

function ViewModel() {
    var self = this;

    //Available types - which will come from serverside
    self.typeDropDown = ko.observableArray(InitialData);

    self.typeValue = ko.observable();

//Explicitly Adding new Row
    self.Inputs = ko.observableArray([new Item(self.typeDropDown[0], '', '', '')]);

    self.removeRow = function (Item) {
        self.Inputs.remove(Item);
    },
    self.addNewRow = function () {
        //push will add a new element to the container without modifying much in DOM
        self.Inputs.push(new Item(self.typeDropDown[0], '', '', ''));
    }

1 个答案:

答案 0 :(得分:0)

该值绑定到Type,但您没有在ViewModel函数中定义Type属性。

如果您添加以下内容,它应该有效:

self.Type = ko.observable("NASA1"); 

到您的viewmodel。

有关示例,请参阅此JSFiddle