2016-03-17 145 views
1

我有一個簡單的計算器下面的代碼。該代碼工作正常,但我希望下拉列表中的值在提交後留在那裏。我將如何做到這一點?基本上,我希望操作員在計算完成後保持選擇狀態。目前,它只是顯示一個「+」,即使總和爲25/5PHP保持下拉值後提交

<?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> 

回答

5

您必須設置爲已提交該選項的selected屬性。所以你必須檢查每個選項的提交值。在我的解決方案中,我使用三元運算符僅爲正確的運算符回顯selected屬性。

<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> 
+0

輝煌。當我回家時我會試試這個。謝謝。 – Tatws24

+0

這是完美的工作。非常感謝。 – Tatws24

+0

我必須說的很好的解決方案 –