tags:

views:

21

answers:

1

I have a form where the user selects field 1, and then selects field 2, which is populated by their choice on field 1.

The problem is that after they are on step 2, field 1 is not showing their choice (even though the selection is still carried in a hidden form field. Im not sure how to do that with the way ive setup the form below. i need to figure out how to mark it with the selected option.

The functions to selecting field 1 and 2 are below

function GetCategoryList(){
 $push .= "<form action=\"main.php\" method=POST>";
 $push .= "<select name=cat>";
 $result = mysql_query("SELECT * FROM `cats`") or trigger_error(mysql_error()); 
 while($row = mysql_fetch_array($result)){ 
  foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } 
   $id = $row['id'];
   $cat = $row['cat'];
   $push .= "<option value=$id>$cat</option>";
 }
 $push .= "</select>";
 $push .= "<input type=submit name=button id=button value=\"Set Category\"></form>";
 return $push;
}

function GetSubCategoryList($cat){
 $push .= "<form action=\"main.php\" method=POST>";
 $push .= "<select name=subcat>";
 $result = mysql_query("SELECT * FROM `subcats` WHERE cat = '$cat'") or trigger_error(mysql_error()); 
 while($row = mysql_fetch_array($result)){ 
  foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } 
   $id = $row['id'];
   $subcat = $row['subcat'];
   $cat = $row['cat'];
   $push .= "<option value=$id>$subcat</option>";

 }
 $push .= "</select>";
 $push .= "<input type=hidden name=cat value=$cat>";
 $push .= "<input type=submit name=button id=button value=\"Set Sub-Category\"></form>";
 return $push;
}

This is the code on the page itself

  Category
<? echo GetCategoryList(); ?>
  <br />

  SubCategory
<? if(isset($_POST['cat'])){ echo GetSubCategoryList($_POST['cat']); } else { echo "<em>select a category</em>"; } ?>
<br />
+1  A: 

You need to mark the selected option with the selected attribute.

function GetCategoryList($selectedId=null) {
//...
    $selected = ($id==$selectedId) ? "selected" : "";
    $push .= "<option $selected value=$id>$cat</option>";
//...
}

echo GetCategoryList(isset($_POST['cat']) ? $_POST['cat'] : null);

(for xhtml it has to be selected="selected")

VolkerK
works like a charm, thanks! Also, if you dont mind, could you explain how you wrote the echo of the function at the bottom, seems cleaner but i dont understand what exactly is going on (i understand the result, just not the specifics)
Patrick
You probably mean the `x?y:z` part. That's the ternary operator, http://docs.php.net/ternary . I just like to avoid creating "one time" variables, though it's sometimes more readable with them. If `_POST[cat]` is set the value is passed to the function, otherwise NULL is passed.
VolkerK