Jump to content

[SOLVED] Drop down list intial value


cs1h

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.