jQuery 如果 myform.valid() 为真,则触发另一个 jQuery 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7675053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery If myform.valid() is true then fire another jQuery function?
提问by HaBo
I have a jQuery function that i would like to execute only if the form validation is true
I have the validation and other jQuery working fine.
the problem is now both validation and other function are executing same time.
I would like to run the other function only if the form validation is true.
here is my script
我有一个 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>
please advise how can i get this done?
请告诉我如何完成这项工作?
采纳答案by Shadow Wizard is Ear For You
If you're using standard plugin, such code should be supported:
如果您使用的是标准插件,则应支持此类代码:
$(document).ready(function() {
$("#myForm").validate({
submitHandler: function(form) {
SomeFuncHere();
}
});
})
The code in submitHandler
should be called after successful validation.
submitHandler
验证成功后应调用中的代码。
Edit: based on your code, try this instead:
编辑:根据你的代码,试试这个:
$("#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;
}
});
回答by Stelloy
回答by Muhammad Usman
You have to use .validate().form()
你必须使用 .validate().form()
if (!$("#myform").validate().form()) {
return false; //doesn't validate
}else
{
//form is validated do your work
}