【问题标题】:Add Same Rule Multiple Fields添加相同规则多个字段
【发布时间】:2013-10-07 15:59:11
【问题描述】:

我正在尝试使用此命名约定向 html 输入元素添加相同的规则:

name="elements[1]"
name="elements[2]"

我正在使用 jQuery 和 jQuery 验证插件:

var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
    element.rules('add', {
    required: true,
    number: true
});

但恐怕 element 不是 jQuery 期望添加规则的那种对象。 我正在接收:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'rules'

非常感谢您的帮助。

【问题讨论】:

标签: javascript jquery validation jquery-validate


【解决方案1】:

使用$(this) 而不是element

element 是 HTML JavaScript 对象。

要添加规则,您需要 jQuery 对象,即 $(this)

var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
    $(this).rules('add', {
    required: true,
    number: true
});

甚至更好

var elements = $("#elementsFieldset :input");
    elements.each(function(){
        $(this).rules('add', {
        required: true,
        number: true
    });

更新

仅当您想为多个元素应用规则时,以下代码才适用于一个元素,请使用上面示例中使用的.each()

$("#elementsFieldset :input").rules("add", { 
  required:true,  
  number:true
});

阅读jQuery Validation Plugin - adding rules that apply to multiple fields评论Sparky

jQuery Validation Plugin

【讨论】:

  • 长版也可以。简短版本仅对列表的第一个元素附加验证......真的不知道为什么它只是sintax问题。
  • 您的第二个版本不正确。在这种情况下,jQuery Validate 的方法需要 .each() 方法。请参阅此答案中的选项 2b:stackoverflow.com/a/9056425/594235
【解决方案2】:

试试这个,

$.each(elements, function(i, element) {
    $(this).rules('add', {// use $(this) instead of element
    required: true,
    number: true
});

或尝试简单地

$("#elementsFieldset :input").rules("add", { 
  required:true,  
  number:true
});

您可以在classadd rule 查看jQuery Validation using the class instead of the name value

【讨论】:

  • 您的第二个版本不正确。在这种情况下,jQuery Validate 的方法需要 .each() 方法。请参阅此答案中的选项 2b:stackoverflow.com/a/9056425/594235
猜你喜欢
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多