1

I'm using the jQuery Validation plugin.

I have two groups of checkboxes, all with the same name. E.g.

<div>
  <input class="category-group-1" type="checkbox" name="category[]" value="a">
  <input class="category-group-1" type="checkbox" name="category[]" value="b">
  <input class="category-group-1" type="checkbox" name="category[]" value="c">
</div>

<div>
  <input class="category-group-2" type="checkbox" name="category[]" value="x">
  <input class="category-group-2" type="checkbox" name="category[]" value="y">
  <input class="category-group-2" type="checkbox" name="category[]" value="z">
</div>

I need to require that at least one checkbox from each group be checked in order to pass validation. But as the validation plugin references fields by name rather than class or ID, I can't work out how to do this.

Any help would be appreciated, thanks.

4
  • please share your javascript Commented Aug 10, 2016 at 14:43
  • I don't have any javascript that's relevant to the question. The javascript I've written so far doesn't contain anything that's relevant to the checkbox fields as I don't know how to do that bit, hence my question. Commented Aug 10, 2016 at 14:50
  • 1
    You can't do it with your current naming scheme. The jQuery Validate plugin mandates unique names. Example: everything in the first grouping is named category[1] while the second grouping is named category[2] Commented Aug 10, 2016 at 17:20
  • @Sparky thanks, I feared that may be the case. Unfortunately, changing the naming scheme isn't an option. Ah well, at least I know to stop trying! Commented Aug 11, 2016 at 8:05

1 Answer 1

-1

Use the each function in jQuery.

$(function(){
    isChecked=false;

    $('.category-group-1').each(function(){
        if ($(this).prop('checked')){
            isChecked=true;
            return;
        }   
    })
    alert(isChecked);
}))
Sign up to request clarification or add additional context in comments.

3 Comments

he wants at least one checkbox checked, not all
@oliv37. Oops. I misunderstood the problem. Fixed.
@Matt thanks, but the question relates specifically to the jQuery Validation plugin.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.