Dynamic Dropdown Menu
Platform: PHP
Published Oct 18, 2006
Updated Oct 18, 2006
A function to build a basic dynamic dropdown menu.
<?php
/*
* Dynamic Dropdown Menu
* by da^hype (shahir reza ali)
* www.codedb.org
* 12/10/2006
*
* $fieldname = Name of the field
* $array = An associative array.
* $firstentry = First option in dropdown
* $lastentry = Last option in dropdown
* $onchange = $onchange designates a JavaScript to run when the user chooses one of the options.
* $selectedkey = Default selected item
*
* Example:
* $_array = array('1'=> 'one', '2'=> 'two', '3'=> 'three');
* echo create_dropdown("numbers", $_array, "Select One", "Dont Know..", FALSE, 2);
*
*/
function create_dropdown($fieldname, $array, $firstentry = FALSE, $lastentry = FALSE, $onchange = FALSE, $selectedkey = " ")
{
$dropdown = ($onchange != FALSE) ? '<select size=1 name="'.$fieldname.'" onchange="'.$onchange.'">' :
'<select size=1 name="'.$fieldname.'">';
if ($firstentry != FALSE) //if $firstentry is not FALSE, set one!!!
$dropdown .= '<option value="0">'.$firstentry.'</option>';
foreach($array AS $value => $name) //loop threw array to create the menu
{
$dropdown .= ($value == $selectedkey) ?
'<option value="'.$value.'" selected="'.$selectedkey.'">'.$name.'</option>' :
'<option value="'.$value.'">'.$name.'</option>';
}
if ($lastentry != FALSE) //if $lastentry is not false, set one!!!
$dropdown .= '<option value="-1">'.$lastentry.'</option>';
$dropdown .= '</select>';
return $dropdown; //return the dropdown menu
}
?>