Jump to content

Retaining selected item from option list, when form re-displays


killdozer

Recommended Posts

Hi I have a list of states using the array method in a form. The drop down menu works fine.  I want to save the user choice,if the form is re-displayed due to a blank field or pattern mismatch.  I know I can use the selected=selected, but don't know wher to put the statement:

My array is:

state_province = array ("list of states", "provinces")

Var in my labels array is "state"=>"state"

Here is my code for the select/option statement:

 

{

if($field == "state")

{

echo "<div class='province_state'><label for='state' size='10'>* Province/State</label><select>";

 

foreach($state_province as $state)

{

echo "\n<option value='$state_province' /> ";

echo $state ;

echo "</option>";

}

echo "</select></div>\n";

 

}

?Is this the correct code to add and where would I add  it?

          if(@$_POST['state'] == $value)

  {

      echo "selected='selected'  ";

  } :confused:

 

[attachment deleted by admin]

This code:

if(@$_POST['state'] == $value)
     {
         echo "selected='selected'  ";
     }

 

Is correct/works in comparing the current array entry to what's selected.

 

Logically you want to insert that code on the <option> tag.

 

Break this line:

echo "\n<option value='$state_province' /> ";   

 

Into:

echo "\n<option value='$state_province' ";
//insert the code to check the selected value here
echo "/> ";  

 

How's that work for ya?

Much cleaner. Thanks for posting.

 

foreach($state_province as $state)
{
    $selected = ($state_province==$_POST['state']) ? ' selected="selected"' : '';
    echo "<option value='($state_province)'{$selected} />{$state}</option>\n";
}

Thanks Guys, I tried both ways, but it still not retaining the selected state or province. I might have sent a slightly older file today, as I was at work. and never had access to my latest file. I attached the current file using "mjdamto" code here. I don't think I did a very good job naming the array, and the field one being state-province, the other state, as I would get confused to which I should use and where in the statement.  Could you take a look at the attachment to see why it's not keeping the state/province as selected. I'm looking forward to your reply.

 

[attachment deleted by admin]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.