I am really stuck here . . . About 5 hours down, lots of time on google and forums.

I am new to PHP - student about 8 weeks into a class. I have a customer form which I must validate - no problem with that. However -

if while filling out the form a field is blank, or doesn't prove valid I must output the form field label in red, and not lose what they have filled out correctly. I have this figured out until I get to a required drop down select for state . . .

In the code below the "<?= $city ?>" works to not lose the city, but I can't figure out how to do the same thing with $state. If the user selects a state, but doesn't enter a last name for example, when the form re-displays the state is always back to <OPTION value="0" selected="selected">-</option> no matter what I have tried.

I'd really, really appreciate some help with this . . . Assignment is due tomorrow!!

Here is a snippet of code:

<td align="right"<?php if(!$city) echo 'class="error"'; ?>>
<span class="style1"></span> City</td>
<td><input name="city" type="text" id="city" value="<?= $city ?>" size="25" maxlength="25" /></td>
</tr>
<tr>
<td align="right"<?php if(!$state) echo 'class="error"'; ?>>
<span class="style1">
</span> State</td>
<td><select name="state" id="state">
<OPTION value="0" selected="selected">-</option>
<OPTION value=AK>AK</option>
<OPTION value=AL>AL</option>
<OPTION value=AR>AR</option>
<OPTION value=AZ>AZ</option>
<OPTION value=CA>CA</option>
<OPTION value=CO>CO</option>

    There are basically two ways to tackle this..

    • You can leave the dropdown as it is, and create an array with select values
    • You can create the dropdown from an array, and see which option was selected in the process.

    As you only have a few options, I'd go with no 1:

    
    $sels = array('AK'=>"", 'AL'=>"", 'AR'=>"", 'AZ'=>"", 'CA'=>"", 'ZO'=>"");
    
    if(isset($_POST['state']))
    
    $sels['$_POST['state']'] = " selected ";
    
    <select name="state" id="state">
    <OPTION value="0">-</option>
    echo "
    <OPTION $sels['AK'] value=AK>AK</option>
    <OPTION $sels['AL'] value=AL>AL</option>
    <OPTION $sels['AR'] value=AR>AR</option>
    <OPTION $sels['AZ'] value=AZ>AZ</option>
    <OPTION $sels['CA'] value=CA>CA</option>
    <OPTION $sels['CO'] value=CO>CO</option>";
    </select>
    
      Write a Reply...