php 表单提交之select下拉列表的使用方法

时间:2016-06-17
select下拉列表即可以作为单选列表,也可以设置其作为多选列表来使用,本文章向大家介绍php select下拉列表如何实现多选以及php服务器端如何获取select选中的值,需要的朋友可以参考一下这篇文章。

html select单选的实现

html select下拉列表作为单选很简单,一般不作任何设置时,默认表示select下拉列表是作为单选的。 例如:

<form action="formSelectData.php" method="POST">
  <input type="text" name="user">
  <br>
  <textarea name="address" rows="5" cols="40"></textarea>
  <br>
  <select name="products">
    <option>option1
    <option>option2
    <option>option3
    <option>option4
  </select>
  <br>
  <input type="submit" value="OK">
</form>

上面实例即表示select下拉列表是作为单选列表的。

html select 多选列表的设置

html select表单元素作为多选列表的设置

<form action="formSelectData.php" method="POST">
  <input type="text" name="user">
  <br>
  <textarea name="address" rows="5" cols="40"></textarea>
  <br>
  <select name="products[]" multiple>
    <option>option1
    <option>option2
    <option>option3
    <option>option4
  </select>
  <br>
  <input type="submit" value="OK">
</form>

从上面实例可以看出,我们只需要为select下拉列表设置multiple属性并将其name属性设置为数组形式即可实现select下拉列表多选。我们只需要按住ctrl键的同时点击列表中的项就可以多选了。

php如何获取表单元素select的值

当select表单元素作为单选列表时,我们直接用$_POST['select_name']或$_GET['select_name'], select_name表示select元素的name属性值。

当select表单元素作为多选列表时,我们也是使用$_POST['key']或$_GET['key']获取select的值,注意key的值是select name属性去掉[]的值;例如上面实例是这样获取select的值:$_POST['products']或$_GET['products'];但还需要注意一点,这个值是一个数组,如果需要获取每个多选列表的值,必须对该数组进行遍历:

<?php
$products=$_POST['products']
foreach($products as $value ){
    print "$value<br>";
}
?>

select元素表单提交总结:

  1. select下拉列表默认是单选的
  2. 要使select下拉列表多选,必须为select设置multiple属性并将其name属性设置为数组形式
  3. select下拉列表作为多选提交表单时,服务器端的值是数组,必须遍历这个数组方可获取每个列表的值。