2013-05-22 75 views
-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; 
} 
?> 

問:問題與設置默認值和PHP記住在選擇框中的值

我如何才能讓產品組別成爲選擇框,而不是類別1的默認值?我試過這個:

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

但它打破了我的功能。當我輸入1並選擇category1,點擊搜索後,選擇框變爲category2。這不是我想要的。我希望此功能能夠像這樣執行:

  1. 記住用戶爲輸入字段和選擇框所做的值。
  2. 爲選擇框設置默認值category2

我怎麼能做到這一點?

+0

http://stackoverflow.com/questions/16683498/refilling-drop的DUP -down菜單選擇-後形式提交驗證/ 16683590?noredirect = 1個#comment24008944_16683590 – Orangepill

回答

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

U可以使用這樣

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