【问题标题】:How to select elements like question1, question2, question3,... in JQuery form validation plug-in?jQuery表单验证插件中如何选择question1, question2, question3,...等元素?
【发布时间】:2009-11-16 04:07:17
【问题描述】:

我正在使用 jQuery 和 jQuery Validation 插件来验证输入。下面是代码。现在有许多输入,如 question1、question2、question3、question4、... 我怎样才能对它们进行验证?我的意思是如何一起选择它们?

$(document).ready(function() {
    $("#item").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});

代码:

 $("input[name^='question']"): {
            required: true,
             minlength:40

        }  

不起作用。

【问题讨论】:

  • 我正在使用JQuery验证插件
  • “全选”是什么意思?由于每个人似乎都误解了您的问题,因此需要进一步澄清。

标签: jquery css-selectors validation


【解决方案1】:

几种方法。您可以使用逗号分隔符:

$("#question1, #question2, #question3")...

你可以使用add():

$("#question1").add("#question2").add("#question3")..

如果 question1 是名称而不是 ID,请使用属性选择器:

$(":input[name^=question]")...

但我建议使用一个类:

<input type="text" name="question1" class="question">
<input type="text" name="question2" class="question">
<input type="text" name="question3" class="question">

与:

$(":input.question")...

【讨论】:

  • 你的回答很好,但不是我想要的。我的问题被你误解了。
  • 在这种情况下需要对您的问题进行一些澄清。
  • 我希望选择器在 $("#item").validate() 中使用。 input[name^='question']: { required: true, minlength:40 } 不起作用。
  • 只输入名称以“问题”开头的输入。
  • 我使用的是Jquery表单验证插件,select的语法用在validate()函数中,如你所见。
【解决方案2】:

假设你的意思是&lt;input type="text" name="question1" /&gt;,那么试试下面的 jquery 选择器:

$("input[name^='question']");

它将返回所有这些元素的列表。

这是如何做到的(假设您发布的代码适用于一个元素):

$(document).ready(function() {
    $("input[name^='question']").validate({
        rules: {
            title: {
                required: true,
                minlength:40
            },
            content: {
                required: true,
                minlength:100,
                maxlength:2000
            }
        },
        messages: {
        }
    });
});

【讨论】:

  • 它是 Jquery 表单验证插件,而不仅仅是 Jquery。
  • input[name^='question']: { required: true, minlength:40 } 不起作用。
  • 不,$("input[name^='question']") 只是表单项中的输入元素,标题和内容是它们的对等元素。
  • "item" 是表单的名称。问题元素是“项目”形式的输入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
相关资源
最近更新 更多