1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Simple Javascript Validation for Checkbox


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>
Bookmark and Share

  1. No comments yet.
(will not be published)
Security Code:

  1. No trackbacks yet.