Repopulating Form Field

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
RobbieL
Forum Commoner
Posts: 31
Joined: Fri Mar 23, 2007 5:57 pm

Repopulating Form Field

Post 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.
thewebdrivers
Forum Commoner
Posts: 41
Joined: Fri Aug 17, 2007 3:32 pm
Location: india
Contact:

Post 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>
RobbieL
Forum Commoner
Posts: 31
Joined: Fri Mar 23, 2007 5:57 pm

Post by RobbieL »

Bloomin' brilliant! Worked a treat!

Really appreciate, thewebdrivers. Thanks!
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post 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.
Post Reply