<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
。那不是我想要的。我希望这个函数像这样执行:
- 记住用户为输入字段和选择框所做的值。
- 设置选择框的默认值
category2
。
我怎么能做到这一点?