How to add validation rule dynamically to checkbox array?

北战南征 提交于 2019-12-13 06:34:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!