PHP keep dropdown value after submit

让人想犯罪 __ 提交于 2020-05-14 07:36:12

问题


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>


回答1:


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>


来源:https://stackoverflow.com/questions/36072238/php-keep-dropdown-value-after-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!