Jump to content

[SOLVED] How to get form to remember selected option?


supratwinturbo

Recommended Posts

I am now trying to make a form remember which color (a select list) they selected before pressing any of the submit buttons. I entered this code into the form:

 

<select name="color">
<option value="red">red</option>
<option value="blue">blue</option>
</select>

 

 

The submit is a GET type. For example, if the user selects blue and then clicks on either one of the "submit" buttons, I want the form to remember/show the blue option. Right now the select list always goes back to red, the first choice. I tried doing a <?php echo $red; ?> and <?php echo $blue; ?> for the option value, but this does not work since the select list needs a value.

 

Link to comment
Share on other sites

Try this on:

<?php
// Default color if it's selected
$color = isset($_GET['color']) ? $_GET['color'] : 'red';

$colors = array('red', 'blue');
echo "<select name=\"color\">\n";
foreach ($colors as $c) {
  echo "<option value=\"$c\"";
  if ($c == $color) echo " selected=\"selected\"";
  echo ">$c</option>\n";
}
echo "</select>\n";
?>

 

Have fun

Link to comment
Share on other sites

<select name="color">
<option value="red"<?php echo (isset($_GET['color']) && $_GET['color'] == 'red') ? ' selected="selected"' : '' ; ?>>red</option>
<option value="blue"<?php echo (isset($_GET['color']) && $_GET['color'] == 'blue') ? ' selected="selected"' : '' ; ?>>blue</option>
</select>

Link to comment
Share on other sites

first off make your options dynamically generated like

<?php
echo "<select name=\"color\">
$options = array("red","blue");
foreach($options as $value){
//This is the trick here
echo "<option value=\"".$value."\";
if($_GET['color'] == $value){
echo " selected=\"yes\"";
}
echo " >".$value."</option>\n";
}
?>

Tell me if you don't understand it, i dind't test this

 

Link to comment
Share on other sites

  • 2 weeks later...

Hi All, Thank you for the replies...however, I was not detailed enough so the solution you all provided works but not the way I intended. Basically, I have what I want to do involves 2 submit buttons. I posted a simple example here:

 

http://www.zendurl.com/supratt/test.php

 

The user has two choices

 

1.) Enter height in meters and then press the CALCULATE button, which results in ValueA box to show the height in feet and ValueB box to show the height in inches.

 

2.) Enter a number in ValueA box, select what unit it is (feet is default) and then press the CONVERT button, which results in ValueB box (inches is default) to show the converted value with the option box with the correct unit. For example, if I enter 1 feet, ValueB box will show 12 with units of inches. This example works fine, but if I enter 1 inch for ValueA and then hit convert, ValueB's value returns 1/12, but the units for both ValueA and ValueB revert to their default units.

 

What I want is to be able to control the options boxes' values (inch or feet) in my PHP code. Here is my code for that page. Can anyone please help me. If I am not clear, please let me know and I will try to explain better:

 

<html>
<head>
</head>

<body>

<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="GET">
<?php

$h_meters = '';
$units_listA = '';
$units_listB = '';
$valueA = '';
$valueB = '';

$Calculate = '';
$Convert = '';
$Operation=$_GET["Operation"];

if(isset($_GET["h_meters"]))
    $h_meters= $_GET["h_meters"];

if(isset($_GET["units_listA"]))
    $units_listA = $_GET["units_listA"];

if(isset($_GET["units_listB"]))
    $units_listB = $_GET["units_listB"];

if(isset($_GET["valueA"]))
    $valueA = $_GET["valueA"];

if(isset($_GET["valueB"]))
    $valueB = $_GET["valueB"];

if(isset($_GET["Calculate"]))
    $Calculate = $_GET["Calculate"];

if(isset($_GET["Convert"]))
    $Convert = $_GET["Convert"];

// Check which submit button got pressed.

// If Calculate button is pressed, convert meters to feet in ValueA textbox and to inch in ValueB textbox.
if($Operation == "Calculate")
{
	$valueA = $h_meters*3.2808399;
	$valueB = $valueA*12;

	$units_listA = "feet";
	$units_listB = "inch";
}

// If Convert is pressed, check what is slected in the options box. If feet is chosen in the units_listA then
// when units_listB should be set to inch and ValueB should be ValueA*12
if($Operation == "Convert")
{
	if($units_listA=="feet")
	{
		$valueB = $valueA*12;

		$units_listA = "feet";
		$units_listB = "inch";
	}
// If units_listB is set to inch, then units_listB should be set to feet and ValueB should be ValueA/12
	else
	{
		$valueB = $valueA/12;

		$units_listA = "inch";
		$units_listB = "feet";
	}
}
?>

Enter height in meters <input type="text" size="12" name="h_meters" value="<?php echo $h_meters; ?>" />
<input type="submit" name="Operation" value="Calculate" style="border-color: red; border-width: 2px;"/>
<hr />

<input type="text" size="12" name="valueA" value="<?php echo $valueA; ?>" />
<select name="units_listA">
<option value="feet" "<?php if($_GET["units_listA"] == "feet") echo("Selected"); ?>">feet</option>	
<option value="inch" "<?php if($_GET["units_listA"] == "inch") echo("Selected"); ?>">inch</option>
</select>

<br />
<input type="submit" name="Operation" value="Convert" style="border-color: red; border-width: 2px;"/>
<br />

<input type="text" size="12" name="valueB" value="<?php echo $valueB; ?>" />
<select name="units_listB">
<option value="inch" "<?php if($_GET["units_listB"] == "inch") echo("Selected"); ?>">inch</option>	
<option value="feet" "<?php if($_GET["units_listB"] == "feet") echo("Selected"); ?>">feet</option>


</body>

</html>

Link to comment
Share on other sites

You can use if statements for the output of the arrays, and use $_SESSIONs or even $_POST to output the submitted choice at the beginning of your <select> statement.  However, on a completely unrelated point, you should check the input and make sure that only numbers were entered (no letters, underscores, etc.)  You should is an is_num() statement for that.  You should also change to using the post method rather than get, as it keeps your URLs more secure and less susceptible to hijacking.

Link to comment
Share on other sites

place a session_start(); at the beginning of your code, before anything is output to the browser.  Then, initialize $_SESSION['metric1'] = $_POST['metric1'] and so on, rather than just using $metric1.  You can then, in the form, set <input type="text" name="metric1" value="<? echo $_SESSION['metric1']; ?>" />

 

Using sessions allows you to keep track of what options were input by the user.  Sessions last until you end them (session_destroy(); and unset($_SESSION);) or when they expire, which is about an hour after initiated, although that's changeable in the php.ini

 

Just a personal note, though...you may want to remove the check for pressing the submit button.  If someone hits enter rather than clicking the button (which should have the same effect), but your script won't function correctly, as it checks if $Operation is set.

Link to comment
Share on other sites

Hi Pyrodude,

 

    I am a little lost with this whole $_SESSION thing...the problem is, I am trying to have the php code control what the drop down value should be.

 

- If user hits Calculate, the php code will reset the $units_listA back to "feet" and $units_listB back to "inch" just in case the user selected both to be "feet" or "inch."

 

- If user hits Convert, the php code will first check what value $units_listA is and either convert "feet" to "inch" or vice versa... and the php code will then set $units_listB to the other value. How come this code has no effect....is it because I need the $_SESSION or something else....

 

	if($Operation == "Convert")
{
	if($units_listA=="feet")
	{
		$valueB = $valueA*12;

		$units_listA = "feet";
		$units_listB = "inch";
	}
// If units_listB is set to inch, then units_listB should be set to feet and ValueB should be ValueA/12
	else
	{
		$valueB = $valueA/12;

		$units_listA = "inch";
		$units_listB = "feet";
	}
}

 

As you can see I am a total newbie at this...

Link to comment
Share on other sites

Let me go back and modify the code you posted for your entire page.  The Working code is as follows (And I modified your code a little bit to make it more to my liking):

 

<?php
// Initialize the variables
if (isset($_POST['h_meters'])) {
    $h_meters = $_POST['h_meters'];
}
if (isset($_POST['units_listA'])) {
    $units_listA = $_POST['units_listA'];
}
if (isset($_POST['units_listB'])) {
    $units_listB = $_POST['units_listB'];
}
if (isset($_POST['valueA'])) {
    $valueA = $_POST['valueA'];
}
if (isset($_POST['valueB'])) {
    $valueB = $_POST['valueB'];
}
if (isset($_POST['Calculate'])) {
    $Calculate = $_POST['Calculate'];
}
if (isset($_POST['Convert'])) {
    $Convert = $_POST['Convert'];
}
?>
<html>
<head>
<title>Conversion</title>
</head>
<body>
<!--- No form action is necessary - If one is not given, it defaults to the current page. --->
<form method="POST">
<?php
// If the h_meters field has been entered in and the Calculate button has been pressed, convert meters to feet in ValueA textbox and to inch in ValueB textbox.
if ((strlen($h_meters)>0) && is_numeric($h_meters) && isset($Calculate)) {
    // Do some math
    $valueA = $h_meters*3.2808399;
    $valueB = $valueA*12;
    $units_listA = "feet";
    $units_listB = "inch";
}

// If valueA field has been entered in and the Convert button pressed, check what is selected in the options box. If feet is chosen in the units_listA then
elseif ((strlen($valueA)>0) && is_numeric($valueA) && isset($Convert)) {
// when units_listB should be set to inch and ValueB should be ValueA*12
    if($units_listA == "feet") {
        $valueB = $valueA*12;
        // Make sure units_listB is set to inches - pointless to make it display as a conversion from feet to feet
        $units_listB = "inch";
    }
    // If units_listB is set to inch, then units_listB should be set to feet and ValueB should be ValueA/12
    else {
        $valueB = $valueA/12;
        // Make sure units_listB is set to inches - pointless to make it display as a conversion from inches to inches
        $units_listB = "feet";
    }
}
else echo "<b>LAME!</b><br />";
?>

Enter height in meters <input type="text" size="12" name="h_meters" value="<?php echo $h_meters; ?>" />
<input type="submit" name="Calculate" value="Calculate" style="border-color: red; border-width: 2px;"/>
<hr />

<input type="text" size="12" name="valueA" value="<?php echo $valueA; ?>" />
<select name="units_listA">
<?php
// Use a foreach loop to loop through an array and establish the drop-down list
foreach(array('inch','feet') as $value) {
    if ($units_listA == $value) { $selected = ' Selected="selected"'; }
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
unset($selected);
}
?>
</select>

<br />
<input type="submit" name="Convert" value="Convert" style="border-color: red; border-width: 2px;"/>
<br />

<input type="text" size="12" name="valueB" value="<?php echo $valueB; ?>" />
<select name="units_listB">
<?php
// Use a foreach loop to loop through an array and establish the drop-down list
foreach(array('inch','feet') as $value) {
    if ($units_listB == $value) { $selected = ' Selected="selected"'; }
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
unset($selected);
}
?>
</select>
</body>

</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.