【问题标题】:Issue with setting the default value and remembering the values in select box in PHP设置默认值并记住 PHP 选择框中的值的问题
【发布时间】:2013-05-22 16:26:38
【问题描述】:
<form name="search" method="post" >
 Seach for: <input type="text" name="find" value="<?php echo (isset($_POST['find']) ? $_POST['find'] : ''); ?>" /> in
 <Select NAME="field">
 <Option VALUE="category1" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category1') ? 'selected="selected"': ''; ?>>category1</option>
 <Option VALUE="category2" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"': ''; ?>>category2</option>
 </Select>
 <input type="submit" name="search" value="Search" />
 </form>
 <?php
    if(!empty($_POST)){
        $options = array('category1'=> array('1' => 'dog', '2' => 'cat'), 'category2' =>array('1'=>'flower', '2'=>'grass'));
        $input = trim($_POST['find']);
        $category = $_POST['field'];
        $output = $options[$category][$input];
        echo $output;
}
?>

问题:

如何使 category2 成为选择框的默认值而不是 category1?我试过这个:

<Option VALUE="category2" <?php
echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"' : '';
?> selected = "selected">category2</option>

但它破坏了我的功能。当我输入1并选择category1时,点击搜索后,选择框变为category2。那不是我想要的。我希望这个函数像这样执行:

  1. 记住用户为输入字段和选择框设置的值。
  2. 为选择框设置默认值category2

我怎样才能做到这一点?

【问题讨论】:

标签: php html


【解决方案1】:

尝试默认为cat2,选择后为结果

  <form method="post"> 
<Select name="field">
 <Option <?php  if(isset($_POST['field']) && $_POST['field'] == "category1")  echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
 <Option <?php if ((isset($_POST['field']) && $_POST['field'] == "category2") OR empty($_POST['field']))  echo 'selected="selected'; ?> VALUE="category2" >category2</option>
 </Select>
 <input type="submit" />
 </form>

【讨论】:

    【解决方案2】:

    你可以这样使用

    <form method="post"> 
    <Select name="field">
     <Option VALUE="category2" >category2</option>
     <Option <?php  if($_POST['field'] == "category1")  echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
     <Option <?php  if($_POST['field'] == "category3")  echo 'selected="selected"'; ?> VALUE="category3" >category3</option>
     </Select>
     <input type="submit" />
     </form>
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      相关资源
      最近更新 更多