我正在使用jQuery、jQuery Mobile和jQuery验证插件
我有一个“密码”字段和一个“记忆密码”复选框。
我希望只有在密码字段被验证后才启用复选框。
以下是HTML中的两个字段
<input type="password" name="password" class="submit required" minlength="6" />
<input type="checkbox" name="rememberpassword" value="remember" />若要启用或禁用复选框,请使用jQuery移动命令
$('[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()方法,而不是测试是否存在错误类,但是在返回错误之前,这个结果在递归中是正确的。
我没有找到检查字段有效性的方法,该字段不会触发完全验证和随后的递归。
任何帮助都将不胜感激。
发布于 2013-10-25 16:05:28
有条件的规则/函数只适用于:
这是,而不是,意思是:
(是的,正如您所看到的,如果您碰巧使用.valid()作为规则条件的一部分,则会导致递归。)
解决方案是使用keyup事件处理函数和方法检查字段的状态。
$(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事件。
我也“取消”复选框,因为,我想,如果它再次被禁用,您不希望它卡在"uncheck“上。
根据jQuery移动文档,当您“通过JavaScript操作复选框”以更新可视化样式时,您需要使用.checkboxradio('refresh')。根据该页面上的示例,它仅适用于以编程方式选中/取消选中复选框时。
https://stackoverflow.com/questions/19585613
复制相似问题