我有一个单选按钮,我想在选中时启用项目。如果选择某个收音机(如第一个收音机或最后一个收音机),如何启用文本输入?
<div>
<div data-bind="foreach: radios">
<label>Radio</label><input type="radio" name="radios"
data-bind="text: Text, value: Value, checked: $parent.radios()[0].Value" />
</div>
</div>
<div>
<input name="enableSomeText" type="text" name="enable_me" data-bind="enable: $parent.radios().SelectedValue" />
</div>
在模型视图中,无线电是一个可观察的数组,其中包含文本条件,默认情况下启用了单选按钮。 [{“Text”:“Rad1”,“Value”:“Winter”},{Text“:”Rad2“,”Value“:”Summer“},...]
答案 0 :(得分:1)
这里的技巧是将checked分配给一个observable然后用它来控制文本框:
<div>
<div data-bind="foreach: radios">
<label data-bind="text: Text"></label>
<input type="radio" name="radios" data-bind="value: Value, checked: $root.selectedRadio" />
</div>
</div>
<div>
<input name="enableSomeText" type="text" name="enable_me" data-bind="enable: selectedRadio() == 'Summer'"/>
</div>
var model = {
selectedRadio: ko.observable(""),
radios: ko.observableArray([{
"Text": "Rad1",
"Value": "Winter"
}, {
"Text": "Rad2",
"Value": "Summer"
}, {
"Text": "Rad3",
"Value": "Fall"
}])
};
ko.applyBindings(model);
答案 1 :(得分:1)
您可以通过绑定$ index而不是value来实现所需的行为。您还可以将计算的observable添加到模型中以从用于绑定的数组中获取实际值,因此您将在viewmodel中同时拥有索引和值。
ko.extenders.position = function(target, index) {
target.position = ko.observable(ko.unwrap(index));
return target;
}
var model = {
selectedRadioIndex: ko.observable(0),
radios: ko.observableArray([{
"Text": "Rad1",
"Value": "Winter"
}, {
"Text": "Rad2",
"Value": "Summer"
}, {
"Text": "Rad3",
"Value": "Fall"
}])
};
model.selectedRadio = ko.computed(function() {
return model.radios()[model.selectedRadioIndex()].Value;
});
ko.applyBindings(model);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
<div data-bind="foreach: radios">
<label data-bind="text: Text"></label>
<input type="radio" name="radios" data-bind="checkedValue: $index, checked: $root.selectedRadioIndex" />
</div>
</div>
<div>
<input name="val" type="text" name="enable_me" data-bind="enable: selectedRadioIndex() == 0" />
</div>
<div>
--- Selected Index: <span data-bind="text: selectedRadioIndex"></span>
</div>
<div>
--- Selected Value: <span data-bind="text: selectedRadio"></span>
</div>
&#13;