php - GET请求后关注HTML选择下拉选项
问题描述
所以我正在制作一个程序,我正在向自己提交一个表格。这个程序是一个非常基本的计算器,因为我是 HTML 和 PHP 的新手。我正在尝试这样做,以便在您提交表单时,选择下拉菜单将保留在最近使用的运算符上。
例如,如果我让计算器执行“5 + 5”,那么我希望提交的表单将运算符下拉菜单保留在“+”上。
这是我的代码:
<?php
// grab the form values from $_HTTP_GET_VARS hash extract($_GET);
// first compute the output, but only if data has been input if(isset($calc) && $operator == "multiply") { // $calc exists as a variable
$prod = $x * $y; } elseif (isset($calc) && $operator == "plus") {
$operator = $plus;
$prod = $x + $y; } elseif (isset($calc) && $operator == "minus") {
$operator = "minus";
$prod = $x - $y; } elseif (isset($calc) && $operator == "divide") {
$sign = "/";
$prod = $x / $y; } else { // set defaults
$x=0;
$y=0;
$prod=0; } ?>
<html> <head>
<title>PHP Calculator Example</title> </head>
<body>
<h3>PHP Calculator (Version 1)</h3>
<p>Multiply two numbers and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<label for="x">x = </label>
<input type="text" name="x" id="x" size="5" value="<?php print $x; ?>"/>
<select name="operator" id="operator">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">*</option>
</select>
<label for="y">y = </label>
<input type="text" name="y" id="y" size="5" value="<?php print $y; ?>"/>
<input type="submit" name="calc" value="Calculate"/>
</form>
<!-- print the result -->
<?php if(isset($calc)) {
print "<p>x $sign y = $prod</p>";
} ?>
</body> </html>
解决方案
为了保持在选择元素中选择的选项该选项必须具有“已选择”属性
<select name="operator" id="operator">
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "plus"){echo "selected";} ?> value="plus">+</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "minus"){echo "selected";} ?> value="minus">-</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "divide"){echo "selected";} ?> value="divide">/</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "multiply"){echo "selected";} ?> value="multiply">*</option>
</select>
希望对您有所帮助。
推荐阅读
- javascript - 拒绝编译或实例化 WebAssembly 模块,因为“wasm-eval”不是允许的脚本来源
- python - Scrapy停止重定向并获取当前url的html内容
- reactive-programming - 无限反应器流的动态合并
- sql-server - 通过 try..catch 在游标中使用事务
- django - 使用模型 slug 将 django url 与视图匹配
- discord.js - 获取机器人自己的消息
- go - GO 在测试设置方法中附加标准输入
- python - Plotly - 将反向条形图添加到现有的正常图
- javascript - 如何从二维数组中提取多列?
- excel - 从用户窗体 VBA 编辑时维护编辑历史记录