0

I have a form with 2 different group of check boxes that are all required to have different names. The type of validation I need is that the user must select at least one option from Group 1 and at least one option from Group 2 before the form allows them to submit. I'm sure there is some way to do this in JQuery or JavaScript but I have little to none experience in both and most of what I have found online requires the name attribute to be the same which I can't have.

<form id="form1" action method="post">

  //Group 1 needs to have at least one option selected

  <input class="check1" type="checkbox" id="Dan_Murphys" name="Dan_Murphys"/>
  <input class="check1" type="checkbox" id="BWS" name="BWS" />
  <input class="check1" type="checkbox" id="First_Choice" name="First_Choice"/>

  //Group 2 needs to have at least one option selected

  <input class="check2" type="checkbox" id="Apple" name="Apple"/>
  <input class="check2" type="checkbox" id="Bread" name="Bread" />
  <input class="check2" type="checkbox" id="Water" name="Water"/>

  <input type="submit" name="SUBMIT" value="Submit">

</form>
SadCoder
  • 3
  • 5
  • Note that the duplicate groups by name however you can easily amend this to group by class instead, and the logic is otherwise identical. Also, it has to be said that it's very strange to not use common names for the grouped checkboxes. – Rory McCrossan Jul 09 '15 at 06:55
  • This form is being hosted in an external program that pulls the results into a table by targeting the check boxes name. So unfortunately each check box needs a unique name. – SadCoder Jul 10 '15 at 01:11

1 Answers1

1

Groups can be targeted using class name. You can check for length of checked elements using class selector:

if($('.check1:checked').length && $('.check2:checked').length){
    // at least one is selected in both group
}
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • It's good to know that I can use classes to target groups of check boxes to get around the unique name problem. However for the life of me I can't seem to get JavaScript working at all. Being my first time I've coded in it I don't know if I'm missing something basic Here is a pastebin of my code if anyone could tweak it so it works http://pastebin.com/GwCHdwHQ – SadCoder Jul 10 '15 at 01:12
  • You will need to wrap the code in document ready event. – Milind Anantwar Jul 10 '15 at 06:04
  • Thank you so much for your help, I got it in the end – SadCoder Jul 13 '15 at 23:36