Can't validate multiple checkboxes

Hi Folks,

I am using jquery.validate.js and can’t seem to validate if one of several checkboxes has been checked. I’ve read through other posts and tried multiple variations and nothing seems to work. I would be grateful for any help. Here is my code.

 <form action="pre-checkout-test.asp" method="post" name="myForm">
<input name="myCheckBox[]" type="checkbox" value="AA"  />Option AA <br />
<input name="myCheckBox[]" type="checkbox" value="BB"  />Option BB <br />
<input name="submit" type="submit" value="submit" />
</form>


<script> 
$('#myForm').validate({
rules: {
"myCheckBox[]": {
                required: true,
                minlength: 1
            }
}});
</script>

If you didn’t use preformatted option when posting code, it disappears from view. :smile:

Edit your post, highlight the code, and click the button at the top of the editor that looks like </> to mark as code.

HTH,

:slight_smile:

UPDATE: I don’t use jQuery validation… ever. I always build my own. If the checkboxes have the same name (not ID, those have to be unique for each element), and let’s say the name is “thisChkbx”:

chkbx = document.forms["formNameHere"].thisChkbx;
var tot = 0, i;
for(i=0; i < chkbx.length; i++){
  if(chkbx[i].checked === true){
    tot++;
    }
  }
if(tot === 0){ alert("Hey!  Check at least ONE checkbox."); return false; }

Thanks WolfShade

Upon a cursory glance at your code, I do not see anything that is actually triggering the validation. Then, again, I don’t use jQuery validation, so the trigger may be something automatic.

If it isn’t automatic, then you can use a bind to activate upon submit… something like:

$('#myForm').on('submit', function(){
// something like the code I suggested
});

V/r,

:slight_smile:

I appreciate your quick response, WolfShade. I have a big honking form with dozens of elements - so I was hoping jquery.validate.js would save some time. Guess there’s no substitute for doing it yourself :smile:

That is something I have believed for a long time. :slight_smile: But, then, I can be a little OCD, sometimes. Control freak. Plus there is just something SATISFYING about getting elbow-deep in code making a customized validation. :smile:

V/r,

:slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.