jQuery Web Design

Allowing fixed number of check box to be checked using jquery

We look at how we can fix the number of check boxes allowed to be checked in a group. Say you want to allow user to choose only 3 check box at maximum, You can do so by using a little bit of jQuery. What we are going to do in this tutorial is that we will have a set of options using check box presented to the user, from which they will be allowed to choose 3 or any number of options at max. If they happen to choose more than 3 then we alert a message and then uncheck the last checked check box and disable the options that are unchecked, so that if they want to choose another option, they first have to uncheck one of the checked check box.

All right enough of check box blah blah blah there. Lets get started with the business. This one here uses the jQuery 1.6, It must work on previous versions too but I have not checked it, If any of you do that please let me know through the comments.

First what you have to do is download jQuery1.6 from the jQuery’s official website and put it in your root directory or where you feel right.

Now we move into the business part, getting our code right.

[code]

<script src="jquery1.6.js" type="text/jscript"></script><script type="text/javascript"><!–mce:1–></script>

[/code]

This is the script that will do the main trick. Keep this before the </head> tag. What it basically does is check if the length of the check box element with class chks with property checked, which gives the total number of checked check box element. If the number is more than 3, it disables all the not checked check boxes. Now to complete the job we put in our HTML inside <body> tag.

[code lang=”php”]
<form id="world" method="get">
<input class="chks" name="countries[]" type="checkbox" value="usa" /> USA

<input class="chks" name="countries[]" type="checkbox" value="canada" /> Canada

<input class="chks" name="countries[]" type="checkbox" value="japan" /> Japan

<input class="chks" name="countries[]" type="checkbox" value="nepal" /> Nepal

<input class="chks" name="countries[]" type="checkbox" value="france" /> France

<input name="submit" type="submit" />
</form>
[/code]

I hope this tutorial was of help. If you are lazy you could download it. You can also see a demo of what it would look like.