Jump to content

Values in a form


regular_dave

Recommended Posts

Hello there,I have created a page in php that contains a form for a tram website where you can select your start destination, end destination, no. of adults etc. The page is both a query page and a result page whereby once you fill in the form it sends the form details to itself and then displays what you have entered. If there is a validation error in the form then the form is recreated on the page but saves the values you have previously entered and displays them in the recreated form. However I can't seem to figure out how to display the value selected in a combo box, if an error occurs then the combo box displays the first value that is in it i.e. "City Square".

 # assign form values when applicable $startstation = $_POST["startstation"];  # assign a value to Start Station $endstation = $_POST["endstation"];  # assign a value to End Station $adults = $_POST["adults"];  # assign a value to No. of Adults $children = $_POST["children"];  # assign a value to No. of Children $tickettype = $_POST["tickettype"]; # assign a value to ticket type $sent = $_POST["sent"]; # assign a value to sent

# the HTML form that can be written dynamically$title = "<h3><u>Fare Calculator</u></h3>";$form = "<form action=\"tramform.php\" method=\"post\"><p>Start Station:	<select name=\"startstation\" selected=\"$startstation\">	<option value=\"City Square\">City Square	<option value=\"Headrow\">Headrow	<option value=\"University\">University$form .= "<p>Number of Adults:<input type=\"text\" name=\"adults\" value=\"$adults\">

Surely as i have typed selected=\"$startstation\" when the form is recreated it should display the value that had been previously selected?How can I solve this?

Link to comment
Share on other sites

You could put your select options in an array and then build your select.This is how you want to make an option "pre-selected".

<option selected value="someValue">TEXT</option>

Option Tag( selected )

<?php$selArray = array('City Square','Headrow','University');$startstation = '';if(isset($_POST["startstation"]))$startstation = $_POST["startstation"];foreach($_POST as $key=>$val){    echo "$val is $key.<br />\n";}echo '<form name="f1" method="post" action="'. $_SERVER['PHP_SELF'] .'">        <select name="startstation">';        foreach($selArray as $i=>$value){          if($startstation == $value){             echo '<option selected value="'. $value .'">'. $value . "</option>\n";             continue;            }            echo '<option value="'. $value .'">'. $value . "</option>\n";        }        echo '</select>      <input type="submit">      </form>';?>

Thanks,

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...