Jump to content

ppopulating select rad and chk input elements with posted data.


horseatingweeds

Recommended Posts

I'm trying to keep some select, radio, and check box elements populated with the posted data after they have been submitted, such as if the form fails validation. Text inputs are easy enough by adding a simple echo $_POST['whatever'] into the value attribute but I can't figure out how to do the other inputs.

 

I've tryed this with a select input:

 

function build_select()
{
$state = 
// a bunch of states
;
$state_arr = explode("|", $state);
for ($i=0; $i < (count($state_arr)); $i++)
{
$default = (isset($_POST['state'])? $_POST['state'] : '');
echo "<option value='" . $state_arr[$i] . "'";
if ($default == $state_arr[$i])
{
echo "selected='selected'";
}
echo ">" . $state_arr[$i] . "</option>";
}
}

 

Which does nothing to the outputted html

<select name="stats">
<option value="0">0
<option value="1" selected>1
</select>

<input type="checkbox" name="sel" checked>

<input type="radio" name="rad" value="1" checked>
<input type="radio" name="rad" value="2">

I'm getting closer. This code works for all of the check elements except for the first one: 'New Puppies'

 

I get an error for the $pup variable not existing in the form. Anyone se what I'm doing wrong?

 

<fieldset>
<legend>What do Your Activities Provide?</legend>
<input type='checkbox' name='chkActivities[]' value='New Puppies'
<?php popActivities($pup); ?>  /><label>Doberman Puppies</label><br />
<input type='checkbox' name='chkActivities[]' value='Adult Dobermans'
<?php popActivities($adult); ?> /><label>Adult Dobermans</label><br />
<input type='checkbox' name='chkActivities[]' value='Trained Dobermans'
<?php popActivities($trained); ?> /><label>Trained Dobermans</label><br />
<input type='checkbox' name='chkActivities[]' value='Stud Service'
<?php popActivities($stud); ?> /><label>Stud Service</label><br />
<input type='checkbox' name='chkActivities[]' value='Doberman Rescue'
<?php popActivities($rescue); ?> /><label>Doberman Rescue</label><br />
</fieldset>

 

function popActivities($a)
{
if (isset($_POST['chkActivities']))
{	
GLOBAL $pup;
$pup = '';
GLOBAL $adult;
$adult = '';
GLOBAL $trained;		
$trained = '';
GLOBAL $stud;
$stud = '';
GLOBAL $rescue;
$rescue = '';
foreach($_POST['chkActivities'] AS $activity)
{
	if ($activity == 'New Puppies')
	{$pup = "checked='checked'";}
	if ($activity == 'Adult Dobermans')
	{$adult = "checked='checked'";}
	if ($activity == 'Trained Dobermans')
	{$trained = "checked='checked'";}
	if ($activity == 'Stud Service')
	{$stud = "checked='checked'";}
	if ($activity == 'Doberman Rescue')
	{$rescue = "checked='checked'";}
}
}
echo $a;
}

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.