我有一个jQuery函数,我想只在表单验证为真时才执行
我有验证和其他jQuery工作正常。
问题是现在验证和其他功能都在同一时间执行。
我想仅在表单验证为真时才运行其他函数。
这是我的剧本
<script>
$(document).ready(function () {
$.validator.addClassRules({
fileName: {
required: true
}
});
$("#myform").validate();
if ($("#myform").valid()) {
$(function () {
$('#myform').submit(function () {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
if ((cboxes > 0) && (nboxes > 0)) {
confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
return false;
}
else {
return true;
}
});
});
}
});
</script>
请告知我该如何完成这项工作?
答案 0 :(得分:5)
如果你正在使用jQuery validate插件,那么valid()方法会返回一个布尔值来指示表单是否成功验证,所以你可以这样做:
if ($("#myform").valid()) {
CallSomeOtherFunction();
}
答案 1 :(得分:3)
如果您使用standard plugin,则应支持此类代码:
$(document).ready(function() {
$("#myForm").validate({
submitHandler: function(form) {
SomeFuncHere();
}
});
})
成功验证后,应调用submitHandler
中的代码。
编辑:根据您的代码,请尝试以下方式:
$("#myform").validate({
submitHandler: function(form) {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
var flag = false;
if ((cboxes > 0) && (nboxes > 0)) {
flag = confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
}
else {
flag = true;
}
return flag;
}
});
答案 2 :(得分:2)
您必须使用.validate().form()
if (!$("#myform").validate().form()) {
return false; //doesn't validate
}else
{
//form is validated do your work
}