Check that at least 1 checkbox is checked using jQuery Validate plugin

I’m trying to ensure that at least one checkbox is selected. I’m using the query validate plugin.

here is the checkbox html


 <!-- Checkbox -->
<div class="control-group">
	<label class="control-label" for="checkboxes">Checkboxes</label>
	<div class="controls">
		<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Students">Students<br>
    		<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Alumni">Alumni<br>
    		<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Business">Business<br>
    		<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Faculty">Faculty<br>
	</div><!-- close controls -->
</div> <!-- close control group -->

Here is all of the html:



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <title>jQuery Validate Example | aLittleCode</title>

	  <meta name="viewport" content="width=device-width">

    <link href="style.css" rel="stylesheet">
    <!-- js files linked at bottom -->

  </head>
  <body>
	<div class="container">
	
	    <div class="page-header">
		    <h1>jQuery Validate Example</h1>
		    <p>with styles from Twitter Bootstrap</p>
	    </div>

		<div class="row">
		<div class="span12">
			<form action="" id="contact-form" class="form-horizontal">
			
			<fieldset>
			    <legend>Sample Contact Form <small>(will not submit any information)</small></legend>
			

			    <!-- password INPUT -->
			    <div class="control-group">
			      <label class="control-label" for="password">password</label>
			      <div class="controls">
			        <input id="password" name="password" type="password" maxlength="50" value="" class="input-xlarge">
			      </div> <!-- close controls -->
			    </div><!-- close control group -->

			    <!-- password confirm INPUT -->
			    <div class="control-group">
			      <label class="control-label" for="password_confirm">password confirm</label>
			      <div class="controls">
			        <input id="password_confirm" name="password_confirm" type="password" maxlength="50" value="" class="input-xlarge">
			      </div> <!-- close controls -->
			    </div><!-- close control group -->

			    <!-- TEXT INPUT -->
			    <div class="control-group">
			      <label class="control-label" for="name">Your Name</label>
			      <div class="controls">
			        <input type="text" class="input-xlarge" name="name" id="name">
			      </div> <!-- close controls -->
			    </div><!-- close control group -->

			    <!-- EMAIL - text input area -->
			    <div class="control-group">
			      <label class="control-label" for="email">Email Address</label>
			      <div class="controls">
			        <input type="text" class="input-xlarge" name="email" id="email">
			      </div><!-- close controls -->
			    </div><!-- close control group -->

			    <!-- Text area -->
			    <div class="control-group">
			      <label class="control-label" for="message">Your Message</label>
			      <div class="controls">
			        <textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
			      </div><!-- close controls -->
			    </div> <!-- close control group -->

			    <!-- select - drop down -->
			    <div class="control-group">
			      <label class="control-label" for="select">Make Selection</label>
			      <div class="controls">
			        <select name="select" id="select" class="input-xlarge" >
        				<option value="">Select Request Type</option>
        				<option value="1">1</option>
        				<option value="2">2</option>
        				<option value="3">3</option>
    				</select>
			      </div><!-- close controls -->
			    </div> <!-- close control group -->

			    <!-- Checkbox -->
			    <div class="control-group">
			      <label class="control-label" for="checkboxes">Checkboxes</label>
			      <div class="controls">
			        <input type="checkbox" name="checkboxes[]" id='checkboxes' value="Students">Students<br>
    				<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Alumni">Alumni<br>
    				<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Business">Business<br>
    				<input type="checkbox" name="checkboxes[]" id='checkboxes' value="Faculty">Faculty<br>
			      </div><!-- close controls -->
			    </div> <!-- close control group -->

			    <!-- Radio -->
			    <div class="control-group">
			      <label class="control-label" for="radio">Radio</label>
			      <div class="controls">
			        <input type="radio" name="radio" id='radio' value="yes">Yes<br>
				    <input type="radio" name="radio" id='radio' value="no" checked="">No
			      </div><!-- close controls -->
			    </div> <!-- close control group -->

      		<div class="form-actions">
            <button type="submit" class="btn btn-primary btn-large">Submit</button>
		      <button class="btn">Cancel</button>
			</div>
			</fieldset>
			</form>
		</div><!-- .span -->
		

		<!-- <div class="offset1 span2">
			<div class="well">
				<h2>Links</h2>
				<h3>Validate Plugin</h3>
				<ul>
					<li><a href="http://docs.jquery.com/Plugins/Validation/">jQuery Validate Plugin</a></li>
					<li><a href="http://docs.jquery.com/Plugins/Validation/validate#toptions">Plugin Options</a></li>
					<li><a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">Author's Plugin Page</a></li>
					<li><a href="https://github.com/jzaefferer/jquery-validation">Github Repository</a></li>
				</ul>
				<h3>Other Assets</h3>
				<ul>
					<li><a href="http://webdesign.tutsplus.com/freebies/exclusive-freebie-the-kudos-web-icon-set/">Kudos Web Icons (free)</a></li>
					<li><a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a></li>
				</ul>
			</div>
		</div> --><!-- .span -->
	</div><!-- .row -->

      <hr>

      <footer>

      </footer>


    </div> <!-- .container -->

<!-- ==============================================
		 JavaScript below! 															-->

<!-- jQuery via Google + local fallback, see h5bp.com -->
	  <script src="assets/js/jquery-1.7.1.min.js"></script>

<!-- Validate plugin -->
		<script src="assets/js/jquery.validate.min.js"></script>

<!-- Scripts specific to this page -->
		<script src="script.js"></script>

  </body>
</html>



Here is my js


$(document).ready(function(){

	// Validate
	// http://bassistance.de/jquery-plugins/jquery-plugin-validation/
	// http://docs.jquery.com/Plugins/Validation/
	// http://docs.jquery.com/Plugins/Validation/validate#toptions
	
		$('#contact-form').validate({
	    rules: {
	
	      name: {
	        minlength: 2,
	        required: true
	      },
	
	      email: {
	        required: true,
	        email: true
	      },
	
	      subject: {
	      	minlength: 2,
	        required: true
	      },
	
	      message: {
	        minlength: 2,
	        required: true
	      },

	      select: {
	
	        required: true
	      },

	      password: {
                required: true,
                minlength: 5
            },
	
	      password_confirm: {
	            required: true,
	            minlength: 5,
	            equalTo: "#password"
	        },

          checkboxes: {
          	//required: true,
          	//minlength: 1
            required: function(elem)
            {
                return $("input.select:checked").length > 0;
            }

          }
	    },
	    messages: {
            name: "Enter your name",

            password: {
                required: "Provide a password",
                rangelength: jQuery.format("Enter at least {0} characters")
            },

            password_confirm: {
                required: "Repeat your password",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            },

            email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address",
                remote: jQuery.format("{0} is already in use")
            },

        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	
	  });
	
}); // end document.ready

I was trying to keep it as simple as possible and found this example here on site point but it doesn’t seem to work how i’m using it. Also i have tried it with and without the array added onto the checkboxes. I’m using the to process it on the php side


checkboxes: {
          	
            required: function(elem)
            {
                return $("input.select:checked").length > 0;
            }

}

I haven’t tested the example, but for what I can see, the following 2 things are wrong:

  • the “name”-attribute. Either remove the “” from the name attribute, or leave it and change your JavaScript: In “rules”, change checkboxes, with “checkboxes” (you need to have the double quotes otherwise a JavaScript error will be thrown)

  • you’re checking for $(“input.select:checked”).length > 0. So, jQuery is going to look for input-fields with the class “select” which are checked. None of your checkboxes have a class-attribute “select”, so you should add that to your checkboxes.

Thanks Denk, but I’m still having trouble. I made the changes and tried both with and without the braces for an array and it is still not working, but there are no errors either. I created a more simplified version with just the checkbox inputs to make it easier to follow:

html:


                <input type="checkbox" name="checkboxes[]" id='checkboxes[]' value="Students">Students<br>
		<input type="checkbox" name="checkboxes[]" id='checkboxes[]' value="Alumni">Alumni<br>
		<input type="checkbox" name="checkboxes[]" id='checkboxes[]' value="Business">Business<br>
		<input type="checkbox" name="checkboxes[]" id='checkboxes[]' value="Faculty">Faculty<br>

js


$(document).ready(function(){
	
	$('#contact-form').validate({
	    rules: {
	      
          "checkboxes[]": { 
          	//required: true,
          	//minlength: 1
            required: function(elem)
            {
                return $("input.select:checked").length > 0;
            }
             
          }
	    },
	    messages: { 
            
            "checkboxes[]": "You must check at least 1 box",

        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	     
	  });
	  
}); // end document.ready

You still haven’t added the class-attribute to your checkboxes and I wouldn’t add the id-attribute…


<input type="checkbox" name="checkboxes[]" value="Students" class="select" />Students<br />
<input type="checkbox" name="checkboxes[]" value="Alumni" class="select" />Alumni<br />
<input type="checkbox" name="checkboxes[]" value="Business" class="select" />Business<br />
<input type="checkbox" name="checkboxes[]" value="Faculty" class="select" />Faculty<br />

I tried that and its still not working. no error messages either


 <input type="checkbox" class="checkboxes" name="checkboxes" id='checkboxes' value="Students">Students<br>
		<input type="checkbox" class="checkboxes"name="checkboxes" id='checkboxes' value="Alumni">Alumni<br>
		<input type="checkbox" class="checkboxes" name="checkboxes" id='checkboxes' value="Business">Business<br>
		<input type="checkbox" class="checkboxes" name="checkboxes" id='checkboxes' value="Faculty">Faculty<br>

I have tried both “checkboxes” and checkboxes (with and without quotes)


$(document).ready(function(){
	
		$('#contact-form').validate({
	    rules: {
	      
          checkboxes: { 
          	//required: true,
          	//minlength: 1
            required: function(elem)
            {
                return $("input.checkboxes:checked").length > 0;
            }
             
          }
	    },
	    messages: { 
            
            checkboxes: "You must check at least 1 box",

        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	     
	  });
	  
}); // end document.ready

Any other ideas

this fixed it


<input type="checkbox" class="checkboxes[]" name="checkboxes[]" value="Students" >aaaaa<br>

         <input type="checkbox" class="checkboxes[]" name="checkboxes[]" value="Students">ccccc<br>

         <input type="checkbox" class="checkboxes[]" name="checkboxes[]" value="Students">vvvvv<br>

         <input type="checkbox" class="checkboxes[]" name="checkboxes[]" value="Students">bbbb<br>


$('#contact-form').validate({
	    rules: {

	    	'checkboxes[]': {required: true}
	    },
	    messages: {

            // 'checkboxes[]': "You must check at least 1 box",

        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	
	  });

Please do not ignore the advice that Denk has been giving you.

If your checkboxes have “checkboxes” as their name, then PHP will not have easy access to all of the checked checkboxes. Instead, you will only get one of them.
Using “checkboxes” is required for the server to most easily process multiple checkboxes.

It is invalid to have more than one id attribute with the same identifier. Each identifier must be unique. Do not use an id attribute on your form elements - they do not help with what you are trying to achieve here.


<input type="checkbox" name="checkboxes[]" value="Students" class="select" />Students<br />
<input type="checkbox" name="checkboxes[]" value="Alumni" class="select" />Alumni<br />
<input type="checkbox" name="checkboxes[]" value="Business" class="select" />Business<br />
<input type="checkbox" name="checkboxes[]" value="Faculty" class="select" />Faculty<br />

Your script will work with the above HTML code once a few adjustments are made.

Instead of this:

checkboxes: ...

use this:


'checkboxes[]': ...

And instead of the class name:

return $("input.checkboxes:checked").length > 0;

Use a name selector instead:


return $('input[name="checkboxes[]"]:checked').length > 0;

And since the configuration is already for the ‘checkbox’ element, you can just use this instead:


return $('[name="' + elem.name + '"]').is(':checked');

Thanks guys. I took out the ids, but i’m still having problems with the synax for the validation.
here is my check box html


<input type="checkbox" name="audience[]" value="Current Students">Current Students<br>
<input type="checkbox" name="audience[]" value="Alumni">Alumni<br>
<input type="checkbox" name="audience[]" value="Business">Business<br>
<input type="checkbox" name="audience[]" value="Faculty">Faculty<br>

i’m using the jquery validate plug in and it needs to go with validation for the other fields in the form (not shown)

here is my validation i’m getting an error when I add:


           "audience[]": {
                required: true,
                minlength: 1
            }

<script type="text/javascript">
    $(document).ready(function(){

        $('#contact-form').validate({
          rules: {

            task_name: {
              minlength: 2,
              required: true
            },

            "audience[]": {
                required: true,
                minlength: 1
            }

            request_desc: {
              minlength: 2,
              required: true
            },

           ...
           ...

            approval_email_3: {
              email: true
            },
          },
          messages: {
                task_name: "Enter a task name",

                "audience[]":"Please select at least one audience"

                request_desc: "Enter a task description",

                goal: "Enter the goal of task",

                support_location: "Enter locations supporting request",

                requester_name: "Enter a Task Name",

                approval_name: "Enter a Task Name",

              requester_email: {
                    required: "Please enter a valid email address",
                    email: "Please enter a valid email address"

                },

                approval_email: {
                    required: "Please enter a valid email address",
                    minlength: "Please enter a valid email address"

                },

                approval_email_2: {

                    email: "Please enter a valid email address"
                },

                approval_email_3: {

                    email: "Please enter a valid email address"
                },
                // end of basic messages
                 event_name: {

                   required: "Please enter an event name"

                  },

                 event_desc: {

                    required: "Please enter a event description"
                  },

                  event_location: {

                    required: "Please enter event location"

                  },

                  completion_date: {
                   required: "Please enter a valid date ex. 01-11-2012"

                  },

                  attendees: {
                   required: "Please enter the number of attendees"

                  },

                  event_date: {
                    required: "Please enter a valid date ex. 01-11-2012"

                  },



            },
          highlight: function(label) {
            $(label).closest('.control-group').addClass('error');
          },
          success: function(label) {
            label
              .text('OK!').addClass('valid')
              .closest('.control-group').addClass('success');
          }

        });

    }); // end document.ready
</script>

Never mind, I was using an older file. It’s working now