mercredi 25 janvier 2017

Add validation to dynamically created checkboxes jQuery

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




Aucun commentaire:

Enregistrer un commentaire