Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

html - Issue with setting the default value and remembering the values in select box in PHP

<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;
}
?>

Question:

How could I make category2 to be the default value for the select box instead of category1? I tried this:

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

but it breaks my function. When I input 1 and select category1, after I clicked search, the select box changed to category2. That is not what I want. I want this function to perform like this:

  1. Remember the values that user make for input field and select box.
  2. Set the default value category2 for the select box.

How could I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try default will be cat2 and after selected will be result

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...