Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable as default value within Menu 1

Status
Not open for further replies.

RENO9

Technical User
Dec 8, 2005
27
GB
I have a form starting with a drop down menu i.e.
Code:
<select name="gangs" onchange="submit()">
     <option value="">Select Gang...</option>
     <option value="A1">HanA - Shop 1</option>
     <option value="A2">HanA - Shop 2</option>
     <option value="B1">HanB - Shop 1</option>
     <option value="B2">HanB - Shop 2</option>
</select>
when a choice is selected the form submits itself back onto the same page and registers the choice as a variable
Code:
$GangNumber = $_POST['gangs'];
the problem is that i want to show the variable as the default choice in the drop down menu when the user continues the form rather than reverting back to "Select Gang..." (As this causes it to lose the variable when the form is submitted again)
I have tried various ways but to no avail i.e.
Code:
selected="<? echo $GangNumber; ?>"

Any suggestions?
Thanks in Advance
 
The way to do it is to add [tt]selected="selected"[/tt] to the option you want selected. So if it is the third option, then add that statement to the third option. This is of course easily done with a simple if clause: if the value from post matches the value I am outputing, then add the attribute. If not, skip to next. How you will do it in your code, I don't know. You can just add this check for every line or store all the values in the array and loop through the array checking values all the way.
 
You have to loop through the options, and output the word "selected" as part of the <option> tag when the value of the option matches your input.

Something like:

Code:
<?php

print '<html><body>';

print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
if (isset($_POST['gangs']))
{
	$gangs = $_POST['gangs'];
}
else
{
	$gangs = '';
}

$gangs_array = array
(
	'A1' => 'HanA - Shop 1',
	'A2' => 'HanA - Shop 2',
	'B1' => 'HanB - Shop 1',
	'B2' => 'HanB - Shop 2'
);

print '<select name="gangs" onchange="submit()"><option value="">Select gang...</option>
';

foreach ($gangs_array as $value => $display)
{
	print '
	<option value="' . $value . '"';
	if ($gangs == $value)
	{
		print ' selected ';
	}
	print '>' . $display . '</option>';
}

print '<br/><input type="submit"></form></body></html>';

?>

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Thanks sleipnir214 for the code, i just added the select closing tag </select> at the end and it worked fine with the rest of the page.

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top