#native_company# #native_desc#
#native_cta#

PopSelect – Populate Form Select Drop Down

By Rational Rabbit
on October 16, 2010

Version: 1.0

Type: Function

Category: HTML

License: GNU General Public License

Description: Completely different version of populating a drop-down from an array. Can be simple or complex depending on the parameters. Supports JavaScript and auto-selection.

This is a little function I use whenever I have a form drop-down box. As time has gone on, I've added extra functions, but it can be used in it's basic form with only 2 parameters: The name of the select tag (also becomes the ID), and the name of an array holding your list items.

I keep several arrays handy in include files (such as a list of state names). An array file would look like this (entire state list included):
Code:

<?PHP
   $State2 = array("Alabama"=>"AL","Alaska"=>"AK","Arizona"=>"AZ","Arkansas"=>"AR","California"=>"CA","Colorado"=>"CO","Connecticut"=>"CT","Delaware"=>"DE","Florida"=>"FL","Georgia"=>"GA","Hawaii"=>"HI","Idaho"=>"ID","Illinois"=>"IL","Indiana"=>"IN","Iowa"=>"IA","Kansas"=>"KS","Kentucky"=>"KY","Louisiana"=>"LA","Maine"=>"ME","Maryland"=>"MD","Massachusetts"=>"MA","Michigan"=>"MI","Minnesota"=>"MN","Mississippi"=>"MS","Missouri"=>"MO","Montana"=>"MT","Nebraska"=>"NE","Nevada"=>"NV","New Hampshire"=>"NH","New Jersey"=>"NJ","New Mexico"=>"NM","New York"=>"NY","North Carolina"=>"NC","North Dakota"=>"ND","Ohio"=>"OH","Oklahoma"=>"OK","Oregon"=>"OR","Pennsylvania"=>"PA","Rhode Island"=>"RI","South Carolina"=>"SC","South Dakota"=>"SD","Tennessee"=>"TN","Texas"=>"TX","Utah"=>"UT","Vermont"=>"VT","Virginia"=>"VA","Washington"=>"WA","West Virginia"=>"WV","Wisconsin"=>"WI","Wyoming"=>"WY");
?>

Save the above in a file, then just include that file in your script and the $State2 array is available for your drop down.

I will start with a brief summary, and try to provide examples following the code.

Code:
<?PHP
   # =================================================================
   #      PopSelect
   # Populate a select drop-down list
   # CurrentVal is the selected option, if any
   # If Auto is set to 1, selection will auto-submit form to the location
   #  URL designated in that option's value.
   # AutoString may be used in auto mode if each option has the same preceeding value.
   #  For instance: "thisfile.php?getvar=" may be used if the option values are all processed
   #  by the same file.
   # kv determines whether the selected option is based on key (0) or value (1)
   # Size is the number of rows
   # Javascript event handlers may be used if Auto is set on. Simply enter the code
   #  for the JS field. Event should be single-quoted in function string.
   # Complex example:
   # PopSelect('Name', $Array, 'Selected, 'ClassName', 0, 1, '../directory/runthisfile.html?var=value',20,'onclick="(DoFunction());"')
   # =================================================================
function PopSelect($sName, $sArray, $CurrentVal, $sClass='', $kv=1, $Auto=0, $AutoString='', $Size=0, $JS="")
{
   $html='<select';
   if(!empty($sClass)){$html .= ' Class="' . $sClass . '" ';}
   $html .= ' name="' . $sName . '" id="' . $sName . '"';
   if($Size)
   {
      $html .= ' size="' . $Size . '"';
   }
   if($Auto)
   {
      $html .= ' onchange="if(options[selectedIndex].value){location = options[selectedIndex].value}"';
      if(!empty($JS))
      {
         $JSCode = strtolower($JS);
         if(substr($JSCode,0,8) == "onchange")
         {
            $JS = substr($JS,10); // Remove "onchange" and starting quote
            $html = substr($html,0,-1) . '; '; // Replace last quote with colin
            $html .= $JS;
         }
         else
         {
            $html .= ' ' . $JS;
         }
      }
   }
   else
   {
      if(!empty($JS))
      {
         $JSCode = strtolower($JS);
         $html .= ' ' . $JS;
      }
   }
   $html .= '>' . "n";
   foreach($sArray as $key => $value)
   {
      if($kv==1){$SelectedVal = $value;}else{$SelectedVal = $key;}
      $html .= '<option value="';
      if(!empty($AutoString))
      {
         $html .= $AutoString . $key . '"';
      }
      else
      {
         $html .= $key . '"';
      }
      if($SelectedVal == $CurrentVal)
      {
         $html .= ' selected';
      }
      $html .= '>' . $value . '</option>' . "n";
   }
   $html .= '</select>';
   return $html;
}
?>

Example 1
So if I just want to have a state drop down, I would state it like this:
Code:

echo PopSelect('State',$State2,'');

If I want to have Virginia selected as the default, I would write
Code:

 echo PopSelect('State',$State2,'VA');

($kv defaults to 1 - "value" of the key/value pair)

Example 2 - Class
Now I want to add a class from my stylesheet, called "States". This defines the style for my drop-down list.
Code:

 echo PopSelect('State',$State2,'VA','States');

Example 3 - Use Key or Value for Selected Item
If What I have is the full state name, and I want to use that as the default selected value, I can switch $kv from the default by setting it to 0.
Code:

 echo PopSelect('State',$State2,'Virginia','States',0);

Example 4 - Auto Select
Let's say I have a file named StateResult.php, and, when I make a selection from the drop-down, I want it to automatically go to the information for that state without having to press a submit button. You can only have one result page, but you can send a query string for the file to process. You would do that like this:
Code:

 echo PopSelect('State',$State2,'Virginia','States',0,1,'StateResult.php?s=');

The value of the key/value pair will be auto-inserted at the end of the string. Other query parameters, of course, can be inserted before the "s=", but they would have to be the same for each selection.

Example 5 - Rows
If I want 3 rows of my drop-down to show, I would add a "3" to the next parameter:
Code:

 echo PopSelect('State',$State2,'Virginia','States',0,1,'StateResult.php?s=',3);

Example 6 - JavaScript
If Auto is set ON, you can add JavaScript to your drop-down.
Code:

echo PopSelect('State',$State2,'Virginia','States',0,1,'StateResult.php?s=',3,'onclick="(DoFunction());"');

Hope you find this useful!