Page 1 of 1

Repopulating Form Field

Posted: Thu Oct 18, 2007 8:42 am
by RobbieL
I've got a form with a drop-down box. The box is within a loop that generates every number from 1 to 30 and then displays it in the box. When the form is submitted and there is a validation error of some sort, I want the drop-down box to be repopulated with the option the user selected.
For some reason though, when the form is reloaded, the value of the drop-down box just sets itself to the default value of "01".

Here's the code for the loop:

Code: Select all

<select name="day">
<? $i=1; while ($i<=30)
{?>
	<? $days=sprintf('%02u', $i);?>
	<option <? if(isset($form['day']) and $form['day']==$days) {?> selected="yes"<? }?> value="<?=$days;?>"><?=$days;?></option>
    <? $i++;?>
<?
}?>
</select>
The variable $days is definetily working, begins the drop-down box lists 01-30. But it doesn't seem to be recognised in the IF statement. Anyone got any ideas what's going on?

Thanks.

Posted: Thu Oct 18, 2007 9:22 am
by thewebdrivers
try this

Code: Select all

<select name="day">
<? $i=1; while ($i<=30)
{?>
   <? $days=sprintf('%02u', $i);?>
   <option <? if(isset($_REQUEST['day']) and $_REQUEST['day']==$days) {?> selected="yes"<? }?> value="<?=$days;?>"><?=$days;?></option>
    <? $i++;?>
<?
}?>
</select>

Posted: Thu Oct 18, 2007 9:30 am
by RobbieL
Bloomin' brilliant! Worked a treat!

Really appreciate, thewebdrivers. Thanks!

Posted: Thu Oct 18, 2007 11:02 am
by nickvd
The best practice to use when dealing with form inputs would be to access them via their superglobals ($_GET or $_POST depending on the form), instead of $_REQUEST, as you are never quite sure where the data contained within that array came from.