Monday, May 10, 2010

JavaScript Validate Multiple check box

How to validate Multiple check box in JavaScript

Usage :This validation can use to least one or more of the checkboxes is required to be checked

Compatibility :



JavaScript Code :
Insert this JavaScript in the head section of the html code.

<script language="javascript1.1">
function validate_form(the_form){
var counter=0;
for (i=0; i< document.form1.checkbox_item.length; i++) {
if ((document.form1.checkbox_item[i].checked)) {
counter+=1;
}
}
if(counter==0){
alert("Please select one or more checkbox");
return false;
}
return true;
}
</script>

Html Code :

<form name="form1" id="form1" action="#" method="post" onsubmit="JavaScript:return validate_form(this);">
checkbox 1<input type="checkbox" name="checkbox_item[]" id="checkbox_item" value="checkbox 1">
checkbox 2<input type="checkbox" name="checkbox_item[]" id="checkbox_item" value="checkbox 2">
checkbox 3<input type="checkbox" name="checkbox_item[]" id="checkbox_item" value="checkbox 3">
<input name="submit" type="submit" value="Submit">
</form>

Demo :



No comments: