adam
adam

Reputation: 147

how to remember the selected value of selected box

How can I 'remember' the selected value of drop down box on submit (using php), For example, once the form is posted on the same page, i want to show the selected value as selected in the selectbox. How can I do that?

<form  name="date" method="post" action="<?=$PHP_SELF?>">

<select name="year" >
<option value="0">Year</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
</select>

<input  type="submit" value="Send" name="send" />   
</form>

Upvotes: 0

Views: 3311

Answers (4)

user613857
user613857

Reputation:

Store the selected value in a text file or database, then go back to it. You can also do session variables or cookies.

Write a PHP to output those <option> tags, and if the value is equal to the one you stored, set the selected="selected" attribute for that <option> tag.

Upvotes: 0

Eddie
Eddie

Reputation: 141

Here is my code for something like this:

                      <select  name="city">
                            <?php
                            foreach($cityArray as $key=>$value){
                                $selected = ($_GET['city']==$key)?'selected="true"':'';
                                echo  '<option '.$selected.' value="'.$key.'">'.$value.'</option>';
                            }
                            ?>
                       </select>

Upvotes: 1

pepe
pepe

Reputation: 9909

The way I do it is as follows:

<select id="birth_month" name="birth_month">

    <option value="<?php echo $birth_month ?>" selected="selected">
        <?php echo $birth_month ?>
    </option>

    <option value="" disabled="disabled">
        --------
    </option>

    <option value="Jan">
        Jan
    </option>

    <option value="Feb">
        Feb
    </option>

    <option value="Mar">
        Mar
    </option>

    etc...

Hope this works for you.

Upvotes: 1

Veger
Veger

Reputation: 37905

Read the selected value with someting like $val = $_POST['year'] and use this value to add the selected='selected' attribute to the correct <option> element.

Upvotes: 1

Related Questions