Forum Moderators: coopster

Message Too Old, No Replies

Need help with dropdown select option

Trying to set the selected value of the dropdown menu from a value in a DB.

         

Rex_Fenris

9:02 pm on Jun 14, 2005 (gmt 0)

10+ Year Member



Hello everyone, I've sort of hit a roadblock. I'm working on a user system using PHP and MySQL. Where I'm stuck is on the "Edit User" page where the admin or user can go in and change the personal information of a user.

Here's the dropdown menu...

<SELECT NAME="NameSuffix">
<OPTION VALUE="">SUFFIX</OPTION>
<OPTION VALUE=""></OPTION>
<OPTION VALUE="Jr.">Jr.</OPTION>
<OPTION VALUE="Sr.">Sr.</OPTION>
<OPTION VALUE="M.D.">M.D.</OPTION>
<OPTION VALUE="Ph.D">Ph.D</OPTION>
<OPTION VALUE="I">I</OPTION>
<OPTION VALUE="II">II</OPTION>
<OPTION VALUE="III">III</OPTION>
</SELECT>

<?php print("$data[6]");?> Gets me the database value from the NameSuffix field. Let's say, for example the value is "Sr.". What do I have to do to get the option menu to have the correct value selected from that?

sned

9:28 pm on Jun 14, 2005 (gmt 0)

10+ Year Member



One way to do it would be to put your option values into an array:

$option_values = array('Jr.','Sr.','M.D.','Ph.D.','I','II','III');

Then, your select statement would look something like:


<select name="NameSuffix">
<option value="">SUFFIX</option>
<option value=""></option>
<?php
foreach($option_values as $id=>$value){
$sel = ($value == $data[6])? 'selected="selected"' : '';
echo "<option $sel value=\"$value\">$value</option>";
}
?>
</select>

Hope that helps ....

-sned

mcibor

9:36 pm on Jun 14, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You need to print SELECTED in option where the value from db is the same. you can do it with this:

<?
$select = array("", "Jr.", "Sr.", "M.D.", "Ph.D", "I", "II", "III");
?>
<SELECT NAME="NameSuffix">
<OPTION VALUE="">SUFFIX</OPTION>
<?
foreach($select as $value){
echo "<OPTION VALUE=\"$value\"";
if ($value == $data[6]) echo "SELECTED";
echo ">$value</OPTION>";
}?>
</SELECT>

I don't know of any other way to do that except to use javascript

Best regards
Michal Cibor

PS Sned was faster than me:)

Rex_Fenris

10:16 pm on Jun 14, 2005 (gmt 0)

10+ Year Member



Worked great! Thanks a ton! :)

coopster

2:09 pm on Jun 15, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



And welcome to WebmasterWorld, Rex_Fenris.