Page 1 of 1

Checkbox validation

Posted: Thu Oct 26, 2006 12:21 am
by hsiwux07
I have searched around the tutorial section prior to this post.
I have few questions to get understood.

Here are the codes:

Code: Select all

<form action="check_valid.php" method="post">
<input type="checkbox" name="maj[]" value="Information Technology">Information Technology<br>
<input type="checkbox" name="maj[]" value="Business Administration">Business Administration<br>
<input type="checkbox" name="maj[]" value="Interpersonal Skills">Interpersonal Skills<br>
<input type="checkbox" name="maj[]" value="Operating Systems">Operating Systems<br>
<input type="checkbox" name="maj[]" value="Network Management">Network Management<br>
<input type="checkbox" name="maj[]" value="Data Communications">Data Communications<br>
<input type="checkbox" name="maj[]" value="Database Management">Database Management<br>
<input type="checkbox" name="maj[]" value="Artifical Intelligence">Artifical Intelligence<br>
<input type="radio" name="sex" value="M" CHECKED>Male<br>
<input type="radio" name="sex" value="F">Female<br>
<input type="submit" value="CHECK ORDER">
</form>

Code: Select all

<?php
foreach($_POST['maj'] as $course)
{
echo $course."<br>";
}

$gen=$_POST['sex'];

if($gen=="M")
{
	echo "GOOD BOY";
}
elseif($gen=="F")
{
	echo "GOOD GAL";
}

?>
Questions abou these code here:
1. How can I make an option in any kind of forms to "SELECT ALL".
2. How about if I want to evaluate uncheck all checkboxes and print "NONE WAS SELECTED" on the output page.

Because when I process this piece of code here would occur the error below:
Warning: Invalid argument supplied for foreach() in c:\program files\easyphp1-8\www\validation\check_valid.php on line 2
Thanks in advance.

Posted: Thu Oct 26, 2006 12:24 am
by s.dot
SELECT ALL = javascript, nothing php about that

To check if no checkboxes were checked, use a call to empty().

Code: Select all

if(empty($_POST['mal']))
{
   echo 'no checkboxes were checked!  bad!';
} else
{
   foreach($_POST['mal'] AS $mal)
   {
      echo $mal;
    }
}

Posted: Thu Oct 26, 2006 12:33 am
by Cameri

Code: Select all

<script type="text/javascript">
 function selectAll() {
  var inputs = document.getElementByTagName('input');
  for(var i=0;i<inputs.length;i++) {
    if (inputs[i].type=="checkbox")
     inputs[i].checked =  true;
   }
 }

 function selectNone() {
  var inputs = document.getElementByTagName('input');
  for(var i=0;i<inputs.length;i++) {
    if (inputs[i].type=="checkbox")
     inputs[i].checked =  false;
   }
 }
</script>

Code: Select all

<span onclick="selectAll();">Select All</span>
<span onclick="selectNone();">Select None</span>
Edit: fixed.