PHP class to generate an HTML <select>
Just a simple class to take the legwork out of knocking up <select>s
This HTML ...
<select name='customer' id='customer'>
<option value='AJ'>Alan Jones</option>
<option value='BL' selected>Barbara Lewis</option>
<option value='TP'>Tony Pike</option>
<option value='RA'>Rupert Asquith</option>
</select>
Was generated with this PHP ...
<?php
$sel = new m3htmlSelect('customer');
$temp = array('AJ' => 'Alan Jones', 'BL' => 'Barbara Lewis', 'TP' => 'Tony Pike');
$sel->addOptions($temp); // Add by array
$sel->addOption('RA', 'Rupert Asquith'); // Or add individually
echo $sel->get('BL'); // Gets HTML with BL as the selected option
class m3htmlSelect
{
private $name;
private $options;
public function __construct($name)
{
$this->name = $name;
$this->options = array();
}
public function addOption($value, $text)
{
$this->options[$value] = $text;
}
public function addOptions($arr)
{
foreach($arr AS $value => $text)
$this->addOption($value, $text);
}
public function get($default=null)
{
$html = "<select name='$this->name' id='$this->name'>\n";
foreach($this->options AS $value => $text)
$html.= "<option value='$value'>$text</option>\n";
if ($default!=null)
$html=str_replace("value='$default'", "value='$default' selected", $html);
$html.= "</select>\n";
return $html;
}
}
?>