Assigning a value a dropdown list

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
To make a particular element in an HTML list be selected, you add the word "selected" to the tag, like so:

Code:
Children 17 or under 
<select name="kids">
   <option value="0">0</option> 
   <option value="1">1</option> 
   <option value="2">2</option> 
   <option value="3" selected>3</option> 
   <option value="4">4</option> 
   <option value="5">5</option> 
   <option value="6">6</option> 
   <option value="7+">7+</option> 
</select>

This is a little tricky to do in PHP. What I usually do is generate the list dynamically and use the ternary operator to insert the "selected" at the appropriate spot:

<?
Code:
echo  'Children 17 or under', "\n",
      '<select name="kids">', "\n";

/* we'll assume that you have all of your options in an array
   called $options, and that the value of the option you want
   selected is in $optionselected. There are, of course, other
   ways to do this.
*/
foreach($options as $option) {
   echo  "\t<option value=\"", $option, "\"",
         ($option == $optionselected ? ' selected : ''),
         ">\n";
}

echo '</select>', "\n";

You can, of course, do this without the loop, but your code looks a little crufty if you do:

Code:
Children 17 or under 
<select name="kids">
   <option value="0"<?=
      $optionselected == '0' ? ' selected' : ''
   ?>>0</option> 
   <option value="1"<?=
      $optionselected == '1' ? ' selected' : ''
   ?>>1</option> 
   <option value="2"<?=
      $optionselected == '2' ? ' selected' : ''
   ?>>2</option> 
   <option value="3"<?=
      $optionselected == '3' ? ' selected' : ''
   ?>>3</option> 
   <option value="4"<?=
      $optionselected == '4' ? ' selected' : ''
   ?>>4</option> 
   <option value="5"<?=
      $optionselected == '5' ? ' selected' : ''
   ?>>5</option> 
   <option value="6"<?=
      $optionselected == '6' ? ' selected' : ''
   ?>>6</option> 
   <option value="7+"<?=
      $optionselected == '7+' ? ' selected' : ''
   ?>>7+</option> 
</select>
 
Back
Top