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 14th, 2010
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 7th, 2011
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.