PHP表单两个select标签POST提交仅获取一个值的问题
问题修复方案
嘿,我帮你找到了问题的根源,其实就是两个小疏忽导致的,咱们来逐一解决:
1. 变量名不匹配(核心问题)
你在获取表单提交的pokemonType值时,把它赋值给了变量$type,但在输出的时候却误用了未定义的$pokemonType变量——这就是为什么属性值显示为空的原因!
2. 重复的ID属性(规范问题)
第二个<select>的默认<option>用了和第一个相同的id="region",虽然这不影响表单数据的提交,但HTML规范要求ID必须是页面唯一的,建议改成id="pokemonType",避免后续可能出现的奇怪问题。
修正后的完整代码
echo("<form method=\"POST\">"); echo ("<select name=\"region\" > <option id=\"region\" selected=\"selected\">Choose Region</option>"); foreach($regions as $option){ echo ("<option value=\"$option\">$option</option>"); } echo("</select>"); echo("<br><br><br>"); //select pokemon type echo ("<select name=\"pokemonType\" style=\"text-align: center\"> <option id=\"pokemonType\" selected=\"selected\">Choose Type</option>"); foreach($types as $option){ echo ("<option value=\"$option\">$option</option>"); } echo("</select>"); echo("<br><br><br><input type=\"submit\" name=\"submit\" value=\"Submit\" />"); echo("</form>"); echo("</div>"); //grab pokemon from pokedex database if (isset($_POST['submit'])) { $type = $_POST['pokemonType']; $region = $_POST['region']; echo("<br> You chose $region and $type"); }
修改后再测试,当你选择Johto(地区)和Water(属性)提交,页面就会正确输出You chose Johto and Water啦!
内容的提问来源于stack exchange,提问作者Mohammed Chowdhury
相关产品推荐
相关产品推荐

