Javascript jQuery 验证未捕获的 TypeError 无法读取未定义的属性“表单”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35473775/
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 validate Uncaught TypeError Cannot read property 'form' of undefined
提问by user3808307
I am using jquery validate http://jqueryvalidation.org/
我正在使用 jquery 验证http://jqueryvalidation.org/
I have a form with a first field added manually (hard coded)
我有一个手动添加第一个字段的表单(硬编码)
Then adding more fields is done programatically. The ARE appended inside the form tags already, into a div #to-append
然后以编程方式添加更多字段。ARE 已经附加在表单标签内,放入一个 div #to-append
The one added manually validates fine.
添加的手动验证很好。
For the rest, I am trying to add the rules like this, every time i add a field:
其余的,我试图添加这样的规则,每次我添加一个字段时:
var $largestID = $("#to-append > div:last > div:first > input:first").attr("id");
console.log($largestID); //throws right id
$($largestID).rules("add", {
required: true,
minlength: 3,
pattern: yt
});
But get the "Uncaught TypeError Cannot read property 'form' of undefined" error stated above.
但是得到上面提到的“Uncaught TypeError Cannot read property 'form' of undefined”错误。
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Sravan
You are adding rule taking ID string.Instead take the element selector, and add rule to that selector.
您正在添加采用 ID 字符串的规则。而是采用元素选择器,并将规则添加到该选择器。
var $largestID = $("#to-append > div:last > div:first > input:first").attr("id");
console.log($largestID); //throws right id
$('#'+$largestID).each(function () {
$(this).rules('add', {
requzired: true,
minlength: 3,
pattern: yt
});
});
Use the $('#'+$largestID) to get the field of that ID, and then add rules.
使用 $('#'+$largestID) 获取该 ID 的字段,然后添加规则。
To add rules to array, use
要将规则添加到数组,请使用
$('#'+$largestID) .each(function () { }
you can even validate the array of names of that element,
您甚至可以验证该元素的名称数组,
$('#'+$largestID).validate({
rules: {
'url[]': {
required: true,
}
}
});
回答by Barmar
There's no need to use the ID. You have a selector that returns the element, add the rule to that directly.
无需使用 ID。您有一个返回元素的选择器,直接向其中添加规则。
$("#to-append > div:last > div:first > input:first").rules("add", {
required: true,
minlength: 3,
pattern: yt
});