There are times when we need to add javascript validation to check if at least one of a group of checkbox options has been checked. Here is a simple function that’ll solve the problem and works in most of the browsers.
<html>
<head>
<title>Imran's checkbox validation</title>
<script language="javascript">
//frm is the form element
function checkForm(frm){
var destCount = frm.elements['dest[]'].length;
var destSel = false;
for(i = 0; i < destCount; i++){
if(frm.elements['dest[]'][i].checked){
destSel = true;
break;
}
}
if(!destSel){
alert('Select one or more destinations');
}
return destSel;
}
</script>
</head>
<body>
Select at least one destination
<form action="" method="post" onsubmit="return checkForm(this);">
<input id="cx" type="checkbox" name="dest[]" value="CX" /> <label for="cx">Cox's Bazar</label><br />
<input id="su" type="checkbox" name="dest[]" value="SU" /> <label for="su">Sundarban</label><br />
<input id="sy" type="checkbox" name="dest[]" value="SY" /> <label for="sy">Sylhet</label><br />
<input id="ch" type="checkbox" name="dest[]" value="CH" /> <label for="ch">Chittagong</label><br />
<br />
<input type="submit" name="Go" value=" Go " />
</form>
</body>
</html>


#1 by Debbie on November 14, 2010 - 11:54 pm
Thanks! Just learning javascript – this was exactly what I needed. Other examples at other sites, way too complicated for a beginner to understand. This is just right. Deb
#2 by Paul Carpenter on June 7, 2011 - 5:33 pm
I find this easier for forms (when tested with PHP on server) to use
id=check name=dest
This means if you check by .id in javascript javascript reads it as an ARRAY of ids. Whilst the[] is not needed on the name and PHP collects the items as an ARRAY.
Example on my website withe extra select all clear all functions as well for the javascript.
#3 by Mallika on September 11, 2012 - 10:51 am
Thanks. Learning about javascript validation. This is somewhat helpful to me.
#4 by Kritika Sharma on November 16, 2012 - 5:28 pm
very good example for beginners..
#5 by reejon on February 15, 2013 - 8:55 pm
its completely right
great!!
thanks a lot ^^
#6 by piyush on March 6, 2013 - 11:11 am
That is the so good example for the understand for the bigginner.thank you
#7 by Aardy jamdagni on May 4, 2013 - 8:22 am
nice example