1

I have the following two checkbox groups:

<fieldset class="CbxGroup">
  <legend>Checkbox Group (required)</legend>
  <label><input type="checkbox" name="cbxGroup1[]" value="one" id="cbxGroup1_0">One </label>
  <br>
  <label><input type="checkbox" name="cbxGroup1[]" value="two" id="cbxGroup1_1">Two </label>
  <br>
  <label><input type="checkbox" name="cbxGroup1[]" value="three" id="cbxGroup1_2">Three</label>
  <br>
  <label><input type="checkbox" name="cbxGroup1[]" value="four" id="cbxGroup1_3">Four </label>
  <br>
  <label><input type="checkbox" name="cbxGroup1[]" value="five" id="cbxGroup1_4">Five </label>
  <br>
</fieldset>

<fieldset class="CbxGroup">
<legend>Checkbox Group (required)</legend>
  <label><input type="checkbox" name="cbxGroup2[]" value="one" id="cbxGroup2_0">One </label>
  <br>
  <label><input type="checkbox" name="cbxGroup2[]" value="two" id="cbxGroup2_1">Two </label>
  <br>
  <label><input type="checkbox" name="cbxGroup2[]" value="three" id="cbxGroup2_2">Three</label>
  <br>
  <label><input type="checkbox" name="cbxGroup2[]" value="four" id="cbxGroup2_3">Four </label>
  <br>
  <label><input type="checkbox" name="cbxGroup2[]" value="five" id="cbxGroup_4">Five </label>
  <br>
</fieldset>

Each checkbox-group (fieldset) is tagged with the same class name. I'd like to validate each GROUP so at least one checkbox is selected in EACH group.

I have the following JQuery but it sees them as a single group rather than two separate ones. Can you help me tweak this code so it validates each group separately?

$('.CbxGroup').each(function() {
        if($('.CbxGroup input[type=checkbox]:checked').length == 0) {
            alert('not selected!');
        }
        else{
            alert('selected!');
        }
    });

This way I can add any number of checkbox-groups and have them all validated rather writing separate chunks of code for each group.

Thank you!

2 Answers 2

2

All you need is to change the selector for the length check:

$('.CbxGroup').each(function() { 
    if($(this).find('input[type=checkbox]:checked').length == 0) { 
        alert('not selected!'); 
    } 
    else{ 
        alert('selected!'); 
    } 
}); 
Sign up to request clarification or add additional context in comments.

Comments

2

This should work:

$('.CbxGroup').each(function() {
    if ($(this).find(':checked').length == 0) {
        alert('not selected!');
    }
    else{
        alert('selected!');
    }
});

Comments

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.