tags:

views:

25

answers:

4

Hi,

I have 1 page that displays a form with various dropdowns that are being populated dynamically.

Snippit

 <td valign="top">
                    <select name="status">
                        <option></option>

                        <?php
                            foreach($statuslst as $status){
                                echo '<option value=' . $status[0] . '>' . $status[1] . '</option>';
                            }
                        ?>
                    </select>
                </td>

I have a 2nd page that also displays this form but also the results from the form. the first form is posting to the 2nd and the 2nd is posting to itself.

I want the items chosen in the first form to be selected when posted to the second form.

Can someone steer me in the right direction here?

Thanks,

Jonesy

A: 
<?php
      foreach($statuslst as $status){
          echo '<option value="'.$status[0].'"'.(in_array($status[0],$_POST['status']) ? ' selected="selected"' : '').'>'. $status[1].'</option>';
      }
 ?>

I think it should work.

MatTheCat
+1  A: 

Taken your form is GET type, you could do something like this on the second page:

<?php
  foreach($statuslst as $status){
    $var = '';
    if($_GET['status'] == $status['0']){$var = ' selected="selected"';}
    echo '<option value="' . $status[0] .'"'. $var .'>' . $status[1] . '</option>';
  }
?>
methode
thanks a lot! just what I needed!
iamjonesy
You're very welcome. Don't forget to validate and null-check your variables.
methode
A: 

You will need to add the selected attribute to the option tags on the 2nd form. Take a look at selected option

Phill Pafford
but how do I set which option is selected?
iamjonesy
@jonesy some good examples have been posted
Phill Pafford
+1  A: 

Don't forgot to check the variable exists using

isset($_GET['status'])

or

isset($_GET['status'])

depending on what you're using, as it's not ideal to check the variable without doing this first.

eg. if (isset($_GET['status')) && $_GET['status'] == $status[0] for example

easyjo
thanks for the tip!
iamjonesy
no problems, otherwise you may get a warning in your logs for checking an empty var
easyjo