jQuery Validation Plugin: Validating Checkboxes with Different Names

Posted by Michael on Stack Overflow See other posts from Stack Overflow or by Michael
Published on 2010-03-15T03:59:37Z Indexed on 2010/03/15 5:09 UTC
Read the original article Hit count: 576

I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked.

I know there are a few posts on here already trying to answer this question. The solution that seems to be most logical to me is the answer posted on Question 1734840, but I can't seem to get it working! What's wrong with my code? Or any other new coding ideas to get this working?

I have set the class on all of them to 'require-one'.

My jQuery code is

 $(document).ready(function(){
    $("#itemForm").validate({

     highlight: function(element, errorClass, validClass) {
     $(element).addClass(errorClass).removeClass(validClass);
     $(element.form).find("label[for=" + element.name + "]")
                    .addClass("radioerror");
  },
  unhighlight: function(element, errorClass, validClass) {
     $(element).removeClass(errorClass).addClass(validClass);
     $(element.form).find("label[for=" + element.name + "]")
                    .removeClass("radioerror");
  },

    rules: {
        'require-one': { 
           required : { 
               depends: function(element) { 
                           var allBoxes = $('.require-one'); 
                           if (allBoxes.filter(':checked').length == 0) { 
                              if (allBoxes.eq(element).length != 0) { 
                                  return true; 
                              } 
                           } 
                           return false; 
                        } 
           } 
        } ,    
    },


    errorPlacement: function(error, element) {
            if ( element.is("#other_descrip") )
                error.appendTo("#othererror" );
            if ( element.is("#itemlist") )
                error.appendTo("#itemerror" );
        }
    });
  });

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about validation