Monday, September 22, 2008

javascript validate array checkbox

we can pass value through php and validate checkbox by these

<html>
<html>
<head>
<script language="JavaScript">
function check()
{
 var a=document.some_form['graduate[]'];
 alert("Length:"+a.length);
 var p=0;
 for(i=0;i<a.length;i++){
  if(a[i].checked){
   alert(a[i].value);
   p=1;
  }
 }
 if (p==0){
  alert('please select at least one check box');
  return false;
 }
 document.some_form.submitted.value='yes';
 return true;
}
</script>
</head>
<body>
<form name="some_form" onsubmit="return check();" method="POST" action="">
<table>
<tr><td>Post Graduate in</td><td>
<input type="checkbox" name="graduate[]" value="history">History
<input type="checkbox" name="graduate[]" value="telugu">Telugu
<input type="checkbox" name="graduate[]" value="Computer sceince">Computer Science
<input type="checkbox" name="graduate[]" value="Mathematics">Mathematics

</td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
<input type="hidden" name="submitted">
</form>
</body>
</html>
<?php
if ($_POST[submitted])
{
$pg=$_POST[graduate];
echo "<pre>";
print_r($pg);
echo "</pre>";
}
?>
ref : www.programmersheaven.com