所以我有一个注册系统,用户可以选择现在使用信用卡付款还是稍后使用支票付款。如果他们选择立即使用信用卡付款,则需要验证保存信用卡信息的字段。但是,如果他们选择稍后通过支票付款,则需要隐藏那些保存信用卡信息的字段,从而也关闭对这些字段的验证。这是我理解应该有效的 jQuery 代码:
$('.cc_check').click(function(){
$('.ccinfo').toggle()
if($(".ccinfo").is(":visible")){
$(".cc").validate({
rules: {
card_number: {
required: true,
digits: true,
creditcard: true
},
card_holder:{
required: true
},
card_month: {
required: true,
digits: true,
minlength: 2,
maxlength: 2,
min: 1,
max: 12
},
card_year: {
required: true,
digits: true,
minlength: 2,
maxlength: 2,
min: 11
}
},
messages: {
card_number: {
required: "Please enter a credit card number"
},
card_holder:{
required: "Please enter a credit card holder"
},
card_month: {
required: "Please enter a credit card expiring month",
min: "That is not a month",
max: "That is not a month"
},
card_year: {
required: "Please enter a credit card expiring year",
min: "That year is in the past"
}
}
});
}
});
下面是相应的 HTML 代码:
<tr>
<td align="right">Pay later when you check-in for camp: </td>
<td align="left"><input type="checkbox" class="cc_check" id="check" name="check" value="check" /></td>
</tr>
<tr class="ccinfo">
<td align="right">Pay with Credit Card</td>
<td align="left"> Now instead of Later</td>
</tr>
<tr class="ccinfo">
<td align="right">Credit Card Number: </td>
<td align="left"><input type="text" class="cc" id="card_number" name="card_number"/></td>
</tr>
<tr class="ccinfo">
<td align="right">Card Holder's Name: </td>
<td align="left"><input type="text" class="cc" id="card_holder" name="card_holder"/></td>
</tr>
<tr class="ccinfo">
<td align="right">Expiration Date: </td>
<td align="left">Month:
<input type="text" id="card_month" class="cc" name="card_month" style="width:30px"/>
Year:
<input type="text" id="card_year" class="cc" name="card_year" style="width:30px"/>
</td>
</tr>
所以我的问题是我真的错过了什么吗?当用户单击带有该类的复选框时,带有 ccinfo 类的表行就会消失。我还检查以确保 if 语句有效,并且当 ccinfo 可见时它会进入其中。我可以不根据类名进行验证吗,因为这就是我正在尝试使用类名 cc 验证各个文本框的方法。
任何帮助将不胜感激,这是我几天来一直在努力解决的问题!
最佳答案
我会在您想要禁用验证的元素上设置 disabled
属性(设置此属性会禁用验证)。考虑到这一点,您的代码变得更加简单,只需调用一次 validate()
(验证设置代码被省略,因为我没有更改它;我肯定会将其移到点击处理程序之外):
$('.cc_check').click(function() {
var $ccInfo = $(".ccinfo");
var $inputs = $(".cc input:not(.cc_check):not(:submit)");
$ccInfo.toggle();
if ($ccInfo.is(":visible")) {
$inputs.removeAttr("disabled");
}
else {
$inputs.attr("disabled", "disabled");
}
});
请参阅此处的工作示例:http://jsfiddle.net/andrewwhitaker/PMTTK/ 。请注意,如果您选中该复选框,则正确的字段将被禁用,并且表单将成功发布。删除 disabled
属性后,将重新启用验证。
关于jquery - 基于复选框的 jQuery 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684951/