我正在使用jQuery,jQuery Mobile和jQuery Validation插件
我有一个“密码”字段和一个“rememberpassword”复选框。
我希望只有在验证密码字段后才启用该复选框。
以下是HTML中的两个字段
<input type="password" name="password" class="submit required" minlength="6" />
<input type="checkbox" name="rememberpassword" value="remember" />
要启用或禁用该复选框,我使用jQuery Mobile命令
$('[name=rememberpassword]').checkboxradio( "enable" ); and
$('[name=rememberpassword]').checkboxradio( "disble" );
我无法弄清楚我可以在验证规则中添加此命令的位置。
我尝试在密码字段的验证规则中添加启用/禁用命令,如下所示:
$(form).validate({
rules: {
password: {
required: {
depends: function(element) {
console.log('In the password depends');
if (!$(element).hasClass('error')) {
$('[name=rememberpassword]').checkboxradio("enable");
} else {
$('[name=rememberpassword]').checkboxradio("disable");
}
return true;
}
}
}
}
});
此方法出现问题时,有效和错误类将添加到元素中,以便仅在密码字段中的第一个数据条目之后进行验证,因此复选框仍然有效。
我还尝试使用.valid()
方法验证表单或密码字段,但只要该字段没有填充某些内容,这似乎就没有做任何事情。
我尝试做同样的事情,但在密码上使用.valid()
方法而不是测试是否存在错误类,但这会导致递归,直到返回错误。
我没有找到一种方法来检查不会触发完整验证和随后的递归的字段的有效性。
任何帮助都将不胜感激。
答案 0 :(得分:2)
条件规则/功能仅适用于:
意味着:
(是的,正如您所见,如果您碰巧使用.valid()
作为规则条件的一部分,您将导致递归。)
解决方案是使用keyup
事件处理函数和the .valid()
method来检查字段的状态。
$(document).on('pageinit', function () { // <- DOM ready handler for jQuery Mobile
// initialize plugin with .validate()
$('#myform').validate({
// your rules & options
});
// fire this function on every key-up event within the password field
$('input[name="password"]').on('keyup', function () {
if ($(this).valid()) { // <- check if password field is valid
$('[name="rememberpassword"]')
.checkboxradio('enable'); // <- enable checkbox
} else {
$('[name="rememberpassword"]')
.checkboxradio('disable') // <- disable checkbox
.attr('checked',false) // <- uncheck checkbox if checked
.checkboxradio('refresh'); // <- refresh checkbox
}
});
});
工作演示:http://jsfiddle.net/6eEBC/
我选择不在插件的onkeyup
回调函数中创建此部分,因为这将适用于表单上每个字段的每个keyup事件。
我也“取消选中”复选框,因为我想,如果它再次被禁用,你不希望它被“检查”。
根据the jQuery Mobile docs,您需要在“通过JavaScript操作复选框”时使用.checkboxradio('refresh')
来更新视觉样式。根据该页面上的示例,它仅适用于以编程方式选中/取消选中复选框。