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

我怎么能做到这一点?

4

2 回答 2

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>
于 2013-05-22T04:53:32.797 回答
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>
于 2013-05-22T08:26:38.363 回答