user1002039
user1002039

Reputation: 860

JQuery Multiple Checkbox Groups Validation

How can I validate Checkbox groups with JQuery? I need to make sure that in each group at least one checkbox is selected. I'd like to use a class to identify the groups, so, the html would look like this:

<!-- checkbox group -->
<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>

Because checkboxes don't have a wrapper element like the select list/menu, I don't know how to pull this off. For single checkboxes I can do something like the following but it does not work for checkbox groups:

Thank you!

$('.CbxSingle').each(function() {
        var CbxCheck = $(this);
        if(!CbxCheck.is(':checked')) {
            // do something
        }
        else{
            // do something else
        }
    });

I'd like something like the following that would validate each group separately:

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

Upvotes: 1

Views: 7754

Answers (3)

sczizzo
sczizzo

Reputation: 3206

I created a slight variation as a fiddle, and it seems to work fine. I think your problem is the .CbxSingle class isn't applied to the inputs, so you might use a different selector like .CbxGroup input[type=checkbox].

Upvotes: 0

Tim Withers
Tim Withers

Reputation: 12059

This might work for what you describe:

var numberChecked=$("input[name='cbxGroup1[]']:checked").length;
if(numberChecked<1)
    alert('none checked');
else
    alert(numberChecked+' checked);

Upvotes: 2

Andrew Odri
Andrew Odri

Reputation: 9432

Perhaps something like this might work:

if($(".CbxSingle input[type=checkbox]:checked").length != 0){
    // Run success code
}else{
    // Run failure code
}

There is actually a very similar reference on the jQuery documentation website for the :checked selector: http://api.jquery.com/checked-selector/

Hope that helps!

Upvotes: 3

Related Questions