gpt4 book ai didi

提交后PHP保留下拉值

转载 作者:行者123 更新时间:2023-12-05 08:42:58 25 4
gpt4 key购买 nike

我有以下用于简单计算器的代码。代码工作正常,但我希望下拉列表中的值在提交后保留在那里。我该怎么做?本质上,我希望运算符(operator)在计算完成后保持选中状态。目前,它只显示一个“+”,即使总和是 25/5。

<?php 

$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$operation = $_POST['operator'];


Switch ($operation) {
case 'add': $answer = $number1 + $number2;
break;
case 'minus': $answer = $number1 - $number2;
break;
case 'divide': $answer = $number1 / $number2;
break;
case 'multiply': $answer = $number1 * $number2;
break;
}


?>

<form name='calculator' method='post' action=''>
<table>
<tr>
<td>
<input name="number1" type="text" value="<?php i if(isset($_POST['number1'])) { echo htmlentities($_POST['number1']);}?>" />
</td>
<td>
<select name="operator">
<option value="add">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">x</option>
</select>
</td>
<td>
<input name="number2" type="text" value="<?php if(isset($_POST['number2'])) { echo htmlentities($_POST['number2']);}?>" />
</td>
<td>
<input name="submit" type="submit" value="=" />
</td>
<td>
<input name="" type="text" value="<?php echo $answer ?>" />
</td>
</tr>
</table>

最佳答案

您必须为提交的选项设置selected 属性。所以你必须检查每个选项的提交值。在我的解决方案中,我使用三元运算符仅为正确的运算符回显 selected 属性。

<select name="operator">
<option value="add" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'add') ? 'selected' : ''; ?>>+</option>
<option value="minus" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'minus') ? 'selected' : ''; ?>>-</option>
<option value="divide" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'divide') ? 'selected' : ''; ?>>/</option>
<option value="multiply" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'multiply') ? 'selected' : ''; ?>>x</option>
</select>

上面的代码有些重复。它不断重复大量的代码和html。如果我们能够排除重复的内容,那就太好了。幸运的是,我们可以通过创建一个存储选项的数组并使用 foreach 循环遍历它们来做到这一点,如下所示:

<?php
$options = [
'add' => '+',
'minus' => '-',
'divide' => '/',
'multiply' => 'x'
];
?>

<select name="operator">
<?php foreach ($options as $key => $label) { ?>
<option value="<?= $key ?>" <?= (isset($_POST['operator']) && $_POST['operator'] == $key) ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>

关于提交后PHP保留下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36072238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com