在PHP中处理表单之—Checkbox

原文翻译自:http://www.html-form-guide.com/php-form/php-form-checkbox.html

 单个checkbox

 形如:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

如果`$_POST['formWheelchair']`的值是"Yes",那么该checkbox被勾选

如果该checkbox未被勾选,那么`$_POST['formWheelchair']`将不被设置

 

如下是PHP处理表单的方式:

<?php
 
if(isset($_POST['formWheelchair']) && 
   $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    
 
?>

isset方法可用于判定`formWheelchair`是否被勾选,如没有则返回false

 

checkbox组合

经常性的情况是多个checkbox,示例如下:

<form action="checkbox-form.php" method="post">
 
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
 
<input type="submit" name="formSubmit" value="Submit" />
 
</form>

请注意checkbox有完全相同的名称,(formDoor[],也请注意每个名字以[]结尾),使用[]代表每一个被勾选的复选框的值组成一个数组在PHP中获取,$_POST[‘formDoor’]将返回一个有被勾选复选框的值组成的数组

 

举个列子,我勾选了所有复选框,$_POST['formDoor']将会返回{A,B,C,D,E}数组,下例是如何取出数组值并显示出来:

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);
 
    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

可见`empty()`可用于数组的判空,`count`用于数组计数

 

检查某一特定选项是否被check

 

function IsChecked($chkname,$value)
    {
        if(!empty($_POST[$chkname]))
        {
            foreach($_POST[$chkname] as $chkval)
            {
                if($chkval == $value)
                {
                    return true;
                }
            }
        }
        return false;
    }

 

 

来自StackOverflow的问答

If your HTML page looks like this:

 

<input type="checkbox" name="test" value="value1">

 

After submitting the form you can check it with:

isset($_POST['test'])

or

if ($_POST['test'] == 'value1') ...

 

posted @ 2016-04-09 16:54  Gabyler  阅读(1294)  评论(0编辑  收藏  举报