HTML选项-当可观察对象为null时显示默认值
knockout.js html option - show default value when observable is null
下面是我在ko.js中绑定下拉菜单的代码
HTML: <select data-bind="options: myList, value: _selectedPart , optionsCaption: 'None'"></select>
myList正在从数据库中填充,并成功显示所有值。
我也可以成功保存一个值。
当不选择任何值时,默认值为None。所以,当没有值(null)为这个字段在DB -我想显示默认选项值为"None",这是不发生的。
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>
设置可观察对象的值为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);
您需要将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
相关文章:
- php代码在textbox更改事件上显示null
- javascript对象显示为null,但object.properties返回数据
- 我的localStorage结果显示了[null,null,“something”]],而不是“”;什么”;
- 如何在网格视图中显示NULL值
- 为什么我的 webGL 上下文返回为 null,但也显示它已被检索
- 序列化的 JSON 对象在控制器处显示为 Null
- 某些 JSON 字段在命中 MVC 控制器方法时显示为 NULL
- app.js显示错误:TypeError:无法调用方法'查询'为null
- 如果字段为null,则在sitecore中显示none
- Dimplejs Bug.当序列不为null时,行不会显示
- 显示null的Javascript对象
- 如何正确使用熨斗可选?像铁页一样使用时,项目显示为null
- 如果集合在MeteorJS中为null或不为null,则显示模板
- TypeError:document.getElementById(..)为null,但不会停止显示
- 使用jquery或javascript显示null cookie值为空白空间
- getElementById()总是显示NULL状态
- Javascript变量未解析,显示为空白或null
- 当显示的内容在数据库中为NULL值时隐藏DIV
- 当JavaScript字符串等于null时,显示从DB获得的空字符串
- 如何保持null从显示在internet explorer