Gle*_*ven 7 javascript jquery jquery-validate
我有一个带有一堆默认禁用的文本框的表单,然后通过使用每个文本框旁边的复选框启用.
启用时,这些文本框中的值必须是有效数字,但在禁用时,它们不需要值(显然).我正在使用jQuery Validation插件来进行此验证,但它似乎没有按照我的预期进行.
当我单击复选框并禁用文本框时,尽管depends我已添加到规则中,但仍然会收到无效字段错误(请参阅下面的代码).奇怪的是,实际发生的是错误消息显示一瞬间然后消失.
以下是复选框和文本框列表的示例:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的jQuery代码
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
忽略每个中隐藏的字段,li因为我使用的是asp.net MVC的Html.Checkbox方法.
Ted*_*Ted 11
使用"忽略"选项(http://docs.jquery.com/Plugins/Validation/validate#toptions)可能是您处理此问题的最简单方法.取决于您在表单上还有什么.对于ie,如果您有其他已禁用的控件但仍需要根据某些原因进行验证,则不会对禁用的项目进行过滤.但是,如果该路由不起作用,则使用其他类进行过滤(使用复选框添加和删除)可以使您到达目的地,但更容易.
即
$('form').validate({
ignore: ":disabled",
...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29406 次 |
| 最近记录: |