设置默认值并记住PHP中选择框中的值的问题

时间:2013-05-22 04:45:55

标签: php html

<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
  3. 我怎么能实现这个目标?

2 个答案:

答案 0 :(得分:0)

尝试默认将是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>

答案 1 :(得分:0)

你可以这样使用

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