如何从PHP的下拉列表中获取所选值?

时间:2016-10-02 22:19:34

标签: php

我无法将选定的下拉列值检索到PHP变量

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>    
</form>
<?php
$selected_val = $_POST['Color'];  // Storing Selected Value In Variable
echo "You have selected :" .$selected_val;  // Displaying Selected Value 
?>
</body>
</html>

请帮忙。

2 个答案:

答案 0 :(得分:1)

我认为你应该使用javascript,我给你简单的脚本,它将为你获得所选选项的价值。用户在选择时更改值时的功能加载。

看看:

&#13;
&#13;
function run() {
    document.getElementById("resultColorValue").innerHTML = document.getElementById("Color").value;
}
&#13;
<p>Choose your Color:</p>
<select id="Color" onchange="run()">  <!--Call run() function-->
     <option value=""></option>
     <option value="red">Red</option>
     <option value="green">Green</option>
     <option value="blue">Blue</option>
     <option value="yellow">Yellow</option>     
</select>

<p>Your color is: </p><p id="resultColorValue"></p>
&#13;
&#13;
&#13;

如果您正在寻找,请告知我们。)

答案 1 :(得分:0)

我建议使用多个

<form action="#" method="post">
  <select name="Color[]">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
    <option value="Pink">Pink</option>
   <option value="Yellow">Yellow</option>
  </select>
  <input type="submit" name="submit" value="Submit" />
</form>

PHP:

<?php
  if(isset($_POST['submit'])) {

     foreach ($_POST['Color'] as $select)
     {
       echo $select;
     }
   }
?>