Reputation: 711
I am working on dynamic form which is radio, checkbox are added dynamically. Unfortunately, I stuck in adding validation.
How to add require attribute to checkboxes ?
Following code
<ol type="a">
<li><input type="radio" name="answer0[]">A</li>
<li><input type="radio" name="answer0[]">A</li>
<li><input type="radio" name="answer0[]">A</li>
</ol>
<ol type="a">
<li><input type="checkbox" name="answer1[]">A</li>
<li><input type="checkbox" name="answer1[]">A</li>
<li><input type="checkbox" name="answer1[]">A</li>
</ol>
First approach as follows
$('ol').each(function (i) {
$(this).find("input:first").prop("required", true);
});
Since input elements have same name radio type works fine. But checkbox required to be checked only first input.
Second
$('ol').each(function (i) {
$("[name='answer"+i+"[]']").rules("add", {required:true});
});
But it gives following error
Cannot read property 'settings' of undefined
How to add validation to checkbox at least one must be checked...
Upvotes: 0
Views: 1471
Reputation: 2759
Okay try this solution:
var rules = {};
$('ol [type="checkbox"], ol [type="radio"]').each(function(i,el){
var name = $(el).attr('name');
if(rules[name] === undefined){
rules[name] = {
required: true
};
}
});
$("#myform").validate({
rules: rules
});
Upvotes: 2
Reputation: 2091
you can try
$('ol').each(function (i) {
$(this).find("input[type='checkbox']").prop("required", true);
});
try checking length of checked checkboxes
$('ol').find('input[type="checkbox"]:checked').length
Upvotes: 0
Reputation: 7067
I'd add the dynamic logic into "rules" directly. I recently solved my own problem where one form has two default submit buttons. Added rules as functions took care of it.
Upvotes: 0