Re: default option

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Jul 19, 2011 at 4:28 AM, Chris Stinemetz
<chrisstinemetz@xxxxxxxxx>wrote:

> Hello,
>
> I am building some select menu's dynamically from a mysql database and
> am courous how to give the menu a default option "Choose".
>
> Below is what I have so far for one of my menu's.
>
> Thank you in advace.
>
>                    <select name="market" id="market"
> onchange="javascript:get(this.parentNode);">
>                    <?php
>                        foreach($market_prefix as $key => $value)
>                            {
>                            $selected = '';
>                            if($value == $market)
>                            {
>                            $selected = 'selected';
>                            }
>                            echo("<option value=$value $selected
> >$value : $market_name[$key]");
>                            }
>                            ?>
>                    </select>


Just add it as the first option. If none of the options have the selected
attribute, the first option will be the selected one.

I'd also recommend you escape the variables you're outputting, on the off
chance they contain HTML-like code.

<select name="market" id="market" onchange="if (this.value != '') {
javascript:get(this.parentNode); }">
  <option value="">Choose...</option>
<?php
  foreach($market_prefix as $key => $value)
  {
    $selected = '';
    if ($value == $market)
    {
      $selected = 'selected';
    }
    echo '<option value="', htmlspecialchars($value), '" ', $selected, '>',
htmlspecialchars($value.' : '.$market_name[$key]), '</option>';
  }
?>
</select>

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux