Limit number of checked checkboxes script

Started by ganeshbala, Apr 15, 2009, 07:30 PM

Previous topic - Next topic

ganeshbala

Limit number of checked checkboxes script

Description: This short but practical script lets you limit the number of checkboxes within a group that can be checked. For example, you may have a list of 5 checkboxes, but wish to allow the user only the ability to check a maximum of 2 at any time. Use this script to accomplish that.

Directions

Step 1: Insert the following script into the <HEAD> section of your page:

<script type="text/javascript">

/***********************************************
* Limit number of checked checkboxes script- by JavaScript Kit ([url=http://www.javascriptkit.com]www.javascriptkit.com[/url])
* This notice must stay intact for usage
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and 100s more
***********************************************/

function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i  ){
checkgroup[i].onclick=function(){
var checkedcount=0
for (var i=0; i<checkgroup.length; i  )
checkedcount =(checkgroup[i].checked)? 1 : 0
if (checkedcount>limit){
alert("You can only select a maximum of " limit " checkboxes")
this.checked=false
}
}
}
}

</script>



Step 2: Add the below sample form into the <BODY> section:

<p>Select your favorite two countries below:</p>



<form id="world" name="world">
<input type="checkbox" name="countries" /> USA<br />
<input type="checkbox" name="countries" /> Canada<br />
<input type="checkbox" name="countries" /> Japan<br />
<input type="checkbox" name="countries" /> China<br />
<input type="checkbox" name="countries" /> France<br />
</form>

<script type="text/javascript">

//Syntax: checkboxlimit(checkbox_reference, limit)
checkboxlimit(document.forms.world.countries, 2)

</script>



As illustrated at the end of the code of Step 2, just call the function checkboxlimit() following the form with the checkboxes in question with the following syntax:

//Syntax: checkboxlimit(checkbox_reference, limit)

For example:

checkboxlimit(document.forms.world.countries, 2)