javascript 在多个动态添加的表单上初始化 jQuery validate() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10986523/
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
Initialize jQuery validate() function on multiple dynamically added forms
提问by tim peterson
It is has been suggested that it is best to initialize a $('#form').validate({})
function on page load rather than on a click event: jquery.form/validate plugin only allow submit if input is changed
有人建议最好$('#form').validate({})
在页面加载而不是点击事件上初始化函数:jquery.form/validate 插件只允许在输入更改时提交
I'm wondering how to do this for multiple dynamically added forms without wrapping the $('#form').validate({})
function inside of a on('click', 'input[type="submit"]',
function.
我想知道如何在不将$('#form').validate({})
函数包装在函数内部的情况下为多个动态添加的表单执行此操作on('click', 'input[type="submit"]',
。
Take this code for example:
以这段代码为例:
var id="some identifier for the specific form that is submitted";
`$('#form'+id).validate({})`
- How does this unique identifier,
id
, which is required to distinguish each form get created in the first place? - And what if you don't know the
id
after the page is loaded because it has been created dynamically, e.g., by AJAX.
- 这个唯一的标识符
id
是如何首先创建的,它是区分每个表单所必需的? - 如果您不知道
id
页面加载后的情况,因为它是动态创建的,例如,通过 AJAX。
I have been doing this but this is is what's notrecommended:
我一直在这样做,但这是不推荐的:
$(document.body).on('click', 'input[type="submit"]', function(){
var id=this.id;
$('#form'+id).validate({});
});
thoughts?
想法?
thanks, tim
谢谢,蒂姆
回答by Sparky
If the form does not exist at all when the page loads, then instead of initializing the .validate()
on submit, I'd initialize it immediately after the form is created...
如果页面加载时表单根本不存在,那么我不会.validate()
在提交时初始化它,而是在创建表单后立即初始化它......
// code that dynamically creates #myNewform, then initialize validate()
$('#myNewform').validate();
(validate()
should not be inside a submit handler because the validation is not initialized until after the submit button is clicked. This leads to issues when the form fails validation and must be submitted a second time. The second submit then re-initializes the plugin on the form a second time. See here, here, and herefor similar issues.)
(validate()
不应在提交处理程序中,因为在单击提交按钮之后才会初始化验证。这会导致表单验证失败并且必须第二次提交时出现问题。第二次提交然后重新初始化插件第二次形成。有关类似问题,请参见 此处、此处和此处。)
For existing form
on page...
对于现有form
的页面...
$(document).ready(function(){
$('#myform').validate();
});
or for multiple form
's sharing same validation options...
或多个form
共享相同的验证选项...
$(document).ready(function(){
('.myform').each(function(){
$(this).validate();
});
});