以下是我在ko.js中绑定下拉列表的代码
HTML:
<select data-bind="options: myList, value: _selectedPart , optionsCaption: 'None'"></select>
myList正在从数据库填充,并成功显示所有值。
我也能成功保存一个值。
问题
当我不选择任何值时,默认值为None。 因此,当数据库中的此字段没有值(null)时,我希望将默认选项值显示为 “无” ,这不会发生。
var _selectedPart = ko.observable();
var itemSelected = // get value from DB;
if (itemSelected) {
_selectedPart(parnerSelected);// works fine //
} else {
// select Default option value as "None"
}
我尝试在HTML中检查null。下面的代码,不起作用:
<select data-bind="options: myList, value: selectedPart == null ? 'None' : selectedPart "></select>
答案 0 :(得分:1)
将observable的值设置为undefined
以触发默认optionsCaption
。
function Sample() {
var self = this;
this.myList = ['A', 'B', 'C'];
this._selectedPart = ko.observable();
this.selectFromDB = function () {
// random item to simulate "get from DB"
var randomIndex = Math.floor(Math.random() * this.myList.length);
var value = self.myList[randomIndex];
self._selectedPart(value);
};
this.reset = function () {
self._selectedPart(undefined);
};
}
ko.applyBindings(new Sample());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<button data-bind="click: selectFromDB">Select Item</button>
<button data-bind="click: reset">Reset</button>
<br>
<select data-bind="options: myList, value: _selectedPart, optionsCaption: 'None'"></select>
您可以通过删除if / else来简化代码:
var itemSelected = // get value from DB;
_selectedPart(itemSelected || undefined);
答案 1 :(得分:0)
您需要将valueAllowUnset
添加到数据绑定中,因为null
不在绑定数组中:
<select data-bind="options: myList,
value: _selectedPart,
optionsCaption: 'None',
valueAllowUnset: true"></select>
见这里:
http://knockoutjs.com/documentation/value-binding.html#using-valueallowunset-with-select-elements