Board index   FAQ   Search  
Register  Login
Board index php forum :: HTML HTML Basics

Assigning a value a dropdown list

Discussing Html . Code , Software , other

Moderators: macek, egami, gesf

Postby swirlee » Mon Jul 21, 2003 8:06 am

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

Code: Select all
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: Select all
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: Select all
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>
User avatar
swirlee
Moderator
Moderator
 
Posts: 2272
Joined: Sat Jul 05, 2003 1:18 pm
Location: A bunk in the back

Return to HTML Basics

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron