0

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>
  1. Input type depends on question which is radio or checkbox
  2. There could be any number of questions answer1[], answer2[], answer3[]

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...

2
  • What plugin you are using for validation ? Commented Jan 25, 2017 at 18:15
  • jQuery validation Commented Jan 25, 2017 at 18:16

3 Answers 3

2

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it works, nice approach getting element name.
0

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.

Comments

0

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

4 Comments

Your approach make all checkboxes require to be checked.
ok then you can check length of checked checkboxes in each ol. check edited answer
Suppose there are 50 questions, I don't think it is good idea to check each questions checkboxes length.
you can loop through all ol wrap it under div, and inside ol loop through input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.