Author Topic: Retain option value from select list  (Read 877 times)

cmarie

  • New Member
  • *
  • Posts: 5
  • Karma: +0/-0
    • View Profile
Retain option value from select list
« on: August 18, 2010, 04:02:42 PM »
I have tried all I know, but can't seem to figure out how to re-display a selected option value from an option list once I have returned to the form from a validation script.  All other text fields in the form are retaining their values through the use of SESSION variables which have been populated from the POST variables submitted by the form.  However, the drop down list for the state portion of the user's address reverts to an unselected value.
 
  My code looks like this:
PHP Code: [Select]
 
 
<tr>
          <
th class="redtext">** State:</th>
             <
td>
            <
select name="UserState" size="1" id="UserState">
                        <?
php
   
require_once ("Includes/statelist.inc.php");
    foreach (
$stinfo as $stname=>$st)
    { 
?>
              <option value="<?php echo ($st); ?>"><?php echo ($stname); ?></option>
                 <?php  ?> //this populates a list of state names to select from
//Session variable is set in validation page
   <?php if(isset ($_SESSION['UserState'])) 
   {
    
//set selected option value
    
$selst=$_SESSION['UserState'];
     echo 
'<option ';
     if (
$selst == $st)
     { echo 
' selected="selected" ';
     }
    echo 
'value="'$st .'">'$stname .'</option>';
    }
?>
            </select>

 
I have been database programming for several years, but this is my first attempt at PHP so any suggestions or comments will be most welcome.
Thanks
 

PHP Coder

  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 130
  • Karma: +0/-0
    • View Profile
    • PHP coder
Re: Retain option value from select list
« Reply #1 on: August 18, 2010, 04:17:03 PM »
Try this :)

PHP Code: [Select]

<select name="UserState" size="1" id="UserState">
<?
php
require_once ("Includes/statelist.inc.php");
foreach (
$stinfo as $stname=>$st) {
  echo 
'<option value="'.$st.'"'.($st==$_SESSION['UserState']?' selected':'').'>'.$stname.'</option>'."\n";
}
?>
</select>
PHP coder for hire

cmarie

  • New Member
  • *
  • Posts: 5
  • Karma: +0/-0
    • View Profile
Re: Retain option value from select list
« Reply #2 on: August 18, 2010, 05:14:25 PM »
Worked perfectly!!!! Thanks so much.
 
I understand everything about your code except the final part.  What part does the ."\n" play in the solution?
 
Thanks again

phphelp

  • Administrator
  • Senior Member
  • *****
  • Posts: 777
  • Karma: +3/-0
    • View Profile
    • PHP Help forum
Re: Retain option value from select list
« Reply #3 on: August 18, 2010, 05:26:10 PM »
This is "new line", just to make generated html code readable. You can just remove it.
Are you experienced in PHP programming and willing to share your knowledge?
Join us at php help forum!