这里我想使用knockout js
将选项文本传递给json对象example Code HTML
<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">
<option value="New" selected="selected">Aluth</option>
<option value="Used">Parana</option>
</select>
<input type="text" name="Mileage" data-bind="disable: VehicleType() === 'New',value: Mileage" class="input-large">
<hr/>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
JS
var ViewModel = function() {
this.VehicleType = ko.observable();
this.Mileage = ko.observable();
this.optionText = ko.observable();
this.VehicleType.subscribe(function(newValue) {
if (newValue === "New") {
this.Mileage(0);
}
}, this);
};
ko.applyBindings(new ViewModel());
如何使用下拉标题填充optionText?
答案 0 :(得分:1)
在列表中添加一个空值选项:
<option value="">- Select -</option>
在此处更新:http://jsfiddle.net/uWyM9/1/
这是你想要实现的目标吗?
<强>更新强>
我不太确定你要做什么,但也许你的意思是你需要绑定到一个动态数组? http://jsfiddle.net/uWyM9/2/
你能详细说明吗?
答案 1 :(得分:1)
您可以采用更加可观察的风格
HTML
<select data-bind="options: vehicleTypes, optionsText: 'Name', value: selectedVehicle">
</select>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
的JavaScript
var ViewModel = function() {
var Vehicle = function(name, type) {
this.Name = name;
this.Type = type;
};
this.vehicleTypes = ko.observableArray([
new Vehicle("Aluth", "New"),
new Vehicle("parana", "Used")
]);
this.selectedVehicle = ko.observable();
this.selectedVehicle.subscribe(function(newValue) {
alert(newValue.Name);
alert(newValue.Type);
}, this);
};
ko.applyBindings(new ViewModel());
以下是完整版:jsfiddle