如何将验证规则动态添加到复选框数组? [英] How to add validation rule dynamically to checkbox array?
问题描述
我正在将输入字段动态附加到div
.我希望检查是否至少检查了一个checkbox
,因为我正在通过使用类将JQuery
验证规则动态添加到输入checkbox
的数组中.
HTML:
I am dynamically appending input fields to div
. I wish to check if at least one checkbox
is checked, for that I am adding JQuery
validation rule dynamically to the array of input checkbox
by using class.
HTML:
<input type="checkbox" name="ans[]" value="opt_' + x + '" class="answer_check">
JavaScript:
JavaScript:
$(".answer_check").rules("add", {required: true, messages: {required: "Please select correct answer/s."}});
我在控制台中遇到以下错误.
I am getting following error in console.
语法错误,无法识别的表达式:label[for='ans[]'], label[for='ans[]'] *, #ans[]-error
Syntax error, unrecognized expression: label[for='ans[]'], label[for='ans[]'] *, #ans[]-error
推荐答案
如果$(".answer_check")
表示多个元素,则不能简单地将其附加到.rules()
方法.开发人员设计了这些方法,仅适用于选择器的第一个匹配元素.
If $(".answer_check")
represents more than one element, then you cannot simply attach it to the .rules()
method. The developer designed these methods to only apply to the first matched element of the selector.
要附加到多个元素,您需要将其包装在jQuery .each()
中.
To attach to multiple elements you'll need to wrap it within a jQuery .each()
instead.
$(".answer_check").each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please select correct answer/s."
}
});
});
此外,尽管您可以在复选框或单选元素的组中共享相同的name
,但是每个分组必须都必须具有唯一 name
或此插件将无法正常工作.
Also, although you can share the same name
throughout a group of checkbox or radio elements, each grouping must have a unique name
or this plugin will not work properly.
示例:
Question 1:
<input type="radio" name="foo" value="yes" />yes
<input type="radio" name="foo" value="no" />no
<input type="radio" name="foo" value="maybe" />maybe
Question 2:
<input type="radio" name="bar" value="yes" />yes
<input type="radio" name="bar" value="no" />no
<input type="radio" name="bar" value="maybe" />maybe
这篇关于如何将验证规则动态添加到复选框数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!