问题描述
有人建议最好在页面加载时初始化 $('#form')。validate({})
函数,而不是点击事件:
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
我想知道如何为多个动态添加的表单执行此操作而不包装 $('#在''click','input [type =submit]',
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.
以此代码为例:
var id="some identifier for the specific form that is submitted";
`$('#form'+id).validate({})`
- 这个唯一标识符
id
是如何区分每个表单创建的第一个地方? - 如果你不知道
id
之后怎么办?页面已加载,因为它是动态创建的,例如,通过AJAX。
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.
我一直在这样做,但这就是不推荐:
I have been doing this but this is is what's not recommended:
$(document.body).on('click', 'input[type="submit"]', function(){
var id=this.id;
$('#form'+id).validate({});
});
想法?
谢谢,
tim
thanks,tim
推荐答案
如果页面加载时表单根本不存在,那么而不是初始化
.validate()
在提交时,我会在创建表单后立即对其进行初始化...
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...
// code that dynamically creates #myNewform, then initialize validate()
$('#myNewform').validate();
(
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 here for similar issues.)
For现有
表格
页面上...
For existing
form
on page...
$(document).ready(function(){
$('#myform').validate();
});
或多个
表格
分享同样的验证选项...
or for multiple
form
's sharing same validation options...
$(document).ready(function(){
('.myform').each(function(){
$(this).validate();
});
});
这篇关于在多个动态添加的表单上初始化jQuery validate()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!