Page 1 of 1

Setting the default or selected value in a select menu

Posted: Fri Feb 16, 2007 2:06 pm
by Wade
Hi there, I'm having an issue trying to get the correct item selected in a drop down menu. I'm populating the menu from one table and pulling the current value from another... the code is as follows:

Code: Select all

<?php 

//Get the Category name based on the CategoryID from user record
$query2 = "SELECT * FROM category WHERE CategoryID='" . $row["CategoryID"] . "'"; 
$result2  = mysql_query($query2) or die ('I cannot connect to the database because: ' . mysql_error());
$row2 = mysql_fetch_array($result2);

//Get all Category names to populate the drop down menu
$query = mysql_query("SELECT category FROM category ORDER BY category"); 

echo ("<SELECT NAME=\"Category\">");
while ($r = mysql_fetch_array($query))
{
$category = $r["category"];
echo "<option value=$category";
if ($category == $row2["Category"]) echo " SELECTED";
echo ">$category</option>";
}
echo("</SELECT></td></tr>");
?>
The list gets populated, but the value from the db doesn't become the selected item in the list...
However looking at the source of the page it looks like it's right...
<SELECT NAME="Category">
<option value=Architectural>Architectural</option>
<option value=Builder>Builder</option>
<option value=Charities>Charities</option>
<option value=City Contact>City Contact</option>
<option value=Consultant>Consultant</option>
<option value=Employee>Employee</option>
<option value=Financial>Financial</option>
<option value=HGOC>HGOC</option>
<option value=Industry>Industry</option>
<option value=Legal>Legal</option>
<option value=Marketing>Marketing</option>
<option value=MD Contact>MD Contact</option>
<option value=Media>Media</option>
<option value=Partners>Partners</option>
<option value=Political SELECTED>Political</option>
<option value=Supplier>Supplier</option>
</SELECT>
Any help is appreciated...

Posted: Fri Feb 16, 2007 2:25 pm
by volka
try

Code: Select all

//Get all Category names to populate the drop down menu
$query = "SELECT category,CategoryID FROM category ORDER BY category"
$result = mysql_query($query) or die(mysql_error().': '.$query);

echo '<select name="Category">';
while ( $r=mysql_fetch_array($result) )
{
	$selected = ($r['CategoryID']==$row['CategoryID']) ? ' selected="selected"': '';
	echo '<option', $selected, '>', htmlentities($category), '</option>';
}
echo '</select>';

Posted: Fri Feb 16, 2007 2:39 pm
by Wade
Thanks! part of the problem was Firefox, even after inserting you code, it did nothing. I switched over to IE and it works... any ideas on why it wouldn't work properly with FF?

Posted: Fri Feb 16, 2007 2:58 pm
by nickvd
put quotes around your values...

value="VALUE" selected="SELECTED"