码迷,mamicode.com
首页 > Web开发 > 详细

在PHP中处理表单之—Checkbox

时间:2016-04-09 18:46:03      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

原文转载自: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‘) ...

 

在PHP中处理表单之—Checkbox

标签:

原文地址:http://www.cnblogs.com/gabygoole/p/5372034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!