与 jQuery 验证绑定的单选选项不起作用 [英] Single select options binding with jQuery validation is not working
问题描述
我正在使用敲除将对象列表绑定到 select
.对象类可以有任意数量的属性
I am binding a list of objects to a select
using knockout. Object Class can have any number of properties
<select id="TheProperty_City"
name="TheProperty_City"
class="required"
data-bind="options: cityList,
optionsText: 'Name',
value: selectedCity,
optionsCaption: '--select the city--'" />
这工作得很好,我可以使用 viewModel.selectedCity().Name
或 viewModel.selectedCity().Value
来加载子元素.
This works perfectly fine and I can use viewModel.selectedCity().Name
or viewModel.selectedCity().Value
for loading child elements.
我的问题是 jQuery 验证.如果我保留上述语句,即使选择后 jQuery 也不会重置错误.
My issue is with jQuery validation. If I leave the statement as above, jQuery does not reset the error even after selection.
我通过在绑定中指定 optionsValue
来修复它,但是 selectedCity
返回标量值而不是整个对象.知道如何保留对象行为或以不同方式进行验证吗?
I fixed it with by specifying the optionsValue
in the bind, but then the selectedCity
returns the scalar value and not the entire object. Any idea how to preserve the object behavior or do the validation differently?
<select id="TheProperty_City"
name="TheProperty_City"
class="required"
data-bind="options: cityList,
optionsText: 'Name',
optionsValue: 'Value', //added the optionsValue
value: selectedCity,
optionsCaption: '--select the city--'" />
当未指定 optionsValue
时,错误仍然存在:
The error stays there when optionsValue
is not specified:
这是我在 selectedCity
上的 Object Watch:
Here's my Object Watch on selectedCity
:
这是在指定 optionsValue
时 selectedCity
上的对象监视:
Here's an Object Watch on selectedCity
when optionsValue
is specified:
推荐答案
问题在于,当将对象作为值处理时,option
元素的值设置为".因此,jQuery 验证失败.您可以编写一个绑定或包装器绑定到通过的 options
绑定并将它们设置为一个值,但我认为最好不要走这条路线.
The issue is that when dealing with objects as the value, the option
elements have their value set to "". The jQuery validation fails because of this. You could write a binding or wrapper binding to the options
binding that goes through and just sets them to a value, but I don't think that it is preferable to go that route.
一个不错的选择是存储值并使用一个dependentObservable 来表示当前选择的对象.
A decent option is to store the value and use a dependentObservable to represent the currently selected object.
它会像:
var viewModel = {
cityList: [{ Name: "Madison", Value: "MSN" }, { Name: "Milwaukee", Value: "MKE" }, { Name: "Green Bay", Value: "GRB" }],
selectedCityValue: ko.observable()
};
viewModel.selectedCity = ko.dependentObservable(function() {
var value = this.selectedCityValue();
return ko.utils.arrayFirst(this.cityList, function(city) {
return city.Value === value;
});
}, viewModel);
使用如下绑定:
<select id="TheProperty_City" name="TheProperty_City" class="required"
data-bind="options: cityList,
optionsText: 'Name',
optionsValue: 'Value',
value: selectedCityValue,
optionsCaption: '--select the city--'" />
此处示例:http://jsfiddle.net/rniemeyer/EgCM3/
这篇关于与 jQuery 验证绑定的单选选项不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!