AAA
AAA

Reputation: 3168

How to echo selected option value first?

I have this drop down where i need to show the years. I want to show the previously chosen seleciton first. I am using this below but it shows me a blank instead of the chosen value...

Code:

 <select name="year">
 <option selected value="<?php echo $previousyear;?>">
 <?php for($i=date('Y'); $i>=1900; $i--)
    echo "<option value='$i' ".(($i == date('Y')?'selected="selected"':'')).">
 $i</option>";
 ?>
 </select></td>
  </tr> 

Upvotes: 1

Views: 5342

Answers (3)

Sam Khan
Sam Khan

Reputation: 2477

This is what you need to replace in the code:

    <?php for($i=date('Y'); $i>=1900; $i--)
    echo "<option value='$i'>$i</option>";
?>

Upvotes: 2

Soroush Khosravi
Soroush Khosravi

Reputation: 190

You can submit your current selection as a GET query and use it.

    if (isset($_GET['current'])) { 
      $previousyear = $_GET['current'];
    } 

<select name="year"> 
<option selected value="<?php echo $previousyear;?>"> 

Upvotes: 1

Marc B
Marc B

Reputation: 360882

You're missing a </option> on that first option where you output $previousyear, so you're ending up generating:

<option selected value="XXX"><option value="2011" selected="selected">2011</option>
                             ^---missing </option>

You've now got 2 selected options, and most likely $previousyear is empty, causing the "empty" option.

Upvotes: 1

Related Questions