Issue with 'selected' value within form

Posted by JM4 on Stack Overflow See other posts from Stack Overflow or by JM4
Published on 2010-06-03T16:46:06Z Indexed on 2010/06/03 17:04 UTC
Read the original article Hit count: 309

Filed under:
|
|

I currently have a form built in which after validation, if errors exist, the data stays on screen for the consumer to correct. An example of how this works for say the 'Year of Birth' is:

<select name="DOB3">
    <option value="">Year</option>
    <?php
        for ($i=date('Y'); $i>=1900; $i--)
  {
    echo "<option value='$i'";
    if ($fields["DOB3"] == $i)
      echo " selected";
    echo ">$i</option>";
  }
  ?>
</select>

If an error is found, the year of birth value returns the year previously entered. I am able to have this work on all field with the exception of my 'State' field. I build the array and function for the drop down with the following code:

<?php

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

    function showOptionsDrop($array, $active, $echo=true){
        $string = '';

        foreach($array as $k => $v){
            $s = ($active == $k)? ' selected="selected"' : '';
            $string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";     
        }

        if($echo) {   echo $string;}
        else {       return $string;}
    }
?> 

I then call the function from within the form using:

<td><select name="State"><option value="">Choose a State</option><?php showOptionsDrop($states_arr, null, true); ?></select></td>

Not sure what I'm missing but would love any assistance if somebody sees the error in my code.

Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about validation