有人建议最好在页面加载时而不是在点击事件时初始化 $('#form').validate({})
函数:jquery.form/validate plugin only allow submit if input is changed
我想知道如何对多个动态添加的表单执行此操作,而不将 $('#form').validate({})
函数包装在 on('click ', 'input[type="submit"]',
函数。
以这段代码为例:
var id="some identifier for the specific form that is submitted";
`$('#form'+id).validate({})`
- 首先如何创建区分每个表单所需的唯一标识符
id
? - 如果您在页面加载后不知道
id
,因为它是动态创建的(例如通过 AJAX),该怎么办?
我一直在这样做,但这是不推荐的:
$(document.body).on('click', 'input[type="submit"]', function(){
var id=this.id;
$('#form'+id).validate({});
});
想法?
谢谢, 蒂姆
最佳答案
如果页面加载时表单根本不存在,那么我不会在提交时初始化 .validate()
,而是在创建表单后立即初始化它...
// code that dynamically creates #myNewform, then initialize validate()
$('#myNewform').validate();
(validate()
不应位于提交处理程序内,因为只有在单击提交按钮后才会初始化验证。当表单验证失败并且必须再次提交时,这会导致问题然后,第二次提交会再次在表单上重新初始化插件。有关类似问题,请参阅 here 、 here 和 here 。)
对于页面上现有的表单
...
$(document).ready(function(){
$('#myform').validate();
});
或者多个表单
共享相同的验证选项...
$(document).ready(function(){
('.myform').each(function(){
$(this).validate();
});
});
关于javascript - 在多个动态添加的表单上初始化 jQuery validate() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10986523/