问题
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:
$(".answer_check").rules("add", {required: true, messages: {required: "Please select correct answer/s."}});
I am getting following error in console.
Syntax error, unrecognized expression: label[for='ans[]'], label[for='ans[]'] *, #ans[]-error
回答1:
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.
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."
}
});
});
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.
Example:
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
来源:https://stackoverflow.com/questions/35811125/how-to-add-validation-rule-dynamically-to-checkbox-array