Jump to content

Recommended Posts

Hi,

 

Does anyone know if there is a simple way to set the initially selected of a drop down list from a value pulled from a database.

 

For example if someone fills out a form saying that there favorite colour is red and they save the form to continue it later. Then when they go back the colour will be set to red as they previously chose.

 

Thanks,

Cs1h

Link to comment
https://forums.phpfreaks.com/topic/143057-solved-drop-down-list-intial-value/
Share on other sites

<?php
$colours = array('blue', 'green', 'red', 'yellow');
$choosenColor = 'red';
foreach($colours as $color){
echo '<option name="'.$color.'"';
if($choosenColor == $color){
echo ' selected';
}
echo '>'.$color.'</option>';
}

 

Something along those lines

something like this would do it :)

 

<select name="state" id="state">
<option value='--Please Select--'>--Please Select--</option>
<?php  
include('data_connect.php');
// Define Variables
  $varname='somevalue';
  $defaultvar='defaultvalue'
// print state select box
$query = "SELECT * FROM table WHERE name='$varname''";
$result = mysql_query($query);
while($row_result = mysql_fetch_array($result)) {
$variable= $row_result["name"];
if ($variable) {
if ($variable!=$defaultvar) { echo "<option value='$variable'>$variable</option>\n";
}
}
}
if ($variable==$defaultvar) { echo "<option value='$variable' selected='selected'>$variable</option>\n";
}
?>
</select>

 

You can define the search variable either by another mysql query hard coded or passed to the page either by session url or form.

I added the selected option outside the loop as there appears to be a bug in fire fox which fails to load consecutive select options when set inside a loop.

 

Hope this helps.

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.