提交后PHP保留下拉值 [英] PHP keep dropdown value after submit

查看:74
本文介绍了提交后PHP保留下拉值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用于简单计算器的代码.该代码工作正常,但是我希望下拉列表中的值在提交后保留在那里.我该怎么做? 本质上,一旦计算完成,我希望操作员保持选中状态.此刻,即使总和为25/5,它也只会显示一个"+".

I have the following code for a simple calculator. The code works fine, but I want the value in the dropdown list to stay there after submitted. How would I do this? Essentially, I want the operator to stay selected once the calculation has been done. At the moment, it just shows a '+', even if the sum is 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属性.

You have to set the selected attribute for the option that was submitted. So you have to check the submitted value for each option. In my solution I am using the ternary operator to echo the selected attribute only for the correct operator.

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

这篇关于提交后PHP保留下拉值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆