HTML Form Select Generator

July 18 2007

A simple function that returns an html select menu. The first parameter is the name of the select menu, the second is the associative array of options, the next is the value you want selected, and the last is a string that you can insert into the select tag for custom id, class, or javascript event handlers.

function form_select($name, $options, $cmpVal = FALSE, $misc="")
{
    $html
= "<select name=\"$name\" $misc>\n";
    foreach(
$options as $k => $v)
    
{
        $selected
= ( $k == $cmpVal ) ? 'selected="selected"' : '' ;
        
$html .= "<option $selected value=\"$k\">$v</option>\n";
    
}
    $html
.= "</select>\n";
    return
$html;
}
## EXAMPLE USAGE ##

$options = array( 1=>'apples', 2=>'oranges', 3=>'pears' );

print
form_select( "Fruits", $options, 2 );

// print a select menu with $misc options such as an id and class
print form_select( "Fruits", $options, 1, 'id="FruitMenu" class="required"' );

Comments

1 ecsyle July 18 2007

This menu helper would be nicer if it could support a multiple select. Perhaps I should update it.

Leave a Comment

Allowed / Requried

Only these elements are allowed in submitted comments:

  • <a href="http://www.mysite.com/">my site</a>
  • <img src="http://www.mysite.com/myimage" alt="image" />
  • <blockquote>quote</blockquote>
  • <em>my emphasized text</em>
  • <strong>my bold text</strong>
  • <code>my code</code>

* = Required fields

Commenting is not available in this section entry.