首页 > 解决方案 > 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>

标签: phphtml

解决方案


为了保持在选择元素中选择的选项该选项必须具有“已选择”属性

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

希望对您有所帮助。


推荐阅读