Jump to content

Retaining Drop Down Select Values After Submitting A Form


kdigital

Recommended Posts

Hello, the following code works for all of my other selects but not the one for height. I know it has something to do with the quotes and HTML symbols. Does anyone know how to fix this? Thanks.

 

<option <?php if(isset($_POST)){if($_POST == "5'0""){echo "selected";}} ?> value="5'0"">5'0"</option>

I would highly suggest creating a function to create and auto-select the options instead of putting the code for each and every option. I typically define my options as an array and then pass the array and the currently select value (if there is one) to a function. Also isset($_POST) is worthless since it will always be set even if there was no form posted. Lastly, I would also consider changing the values of the options to something that won't cause problems with HTML markup. The displayed label can still be with the quote marks though. In my example below, I used what 'appears' to be a decimal value, but is just the feet/inches separated by a period.

 

This is just a rough example

<?php

$height_options = array(
'5.0' => "5'0\"";
'5.2' => "5'2\"";
'5.4' => "5'4\"";
'5.6' => "5'6\"";
'5.8' => "5'8\"";
'5.10' => "5'10\"";
'5.0' => "6'0\"";
);

function createOptions($optionsAry, $selectValue=false)
{
$optionsHTML = '';
foreach($optionsAry as $value => $label)
{
    $value = htmlspecialchars($value);
    $label = htmlspecialchars($label);
    $selected = ($selectValue===$value) ? ' selected="selected"' : '';
    $optionsHTML .= "<option value='{$value}'>{$label}</option>\n";
}
return ;
}

?>

<select name="height">
<>php echo createOptions($height_options, $_POST['height']); ?>
</select>

A nice and concise example above. I cleaned up Psyco's code a bit from the rough example:

 

$height_options = array(
'5.0' => "5'0\"",
'5.2' => "5'2\"",
'5.4' => "5'4\"",
'5.6' => "5'6\"",
'5.8' => "5'8\"",
'5.10' => "5'10\"",
'5.0' => "6'0\"",
);

function createOptions($optionsAry, $selectValue=false)
{
$optionsHTML = '';
foreach($optionsAry as $value => $label)
{
    $label = htmlspecialchars($label);
    $selected = ($selectValue === $value) ? ' selected="selected"' : '';
    $optionsHTML .= "<option value='{$value}'{$selected}>{$label}</option>\n";
}
return $optionsHTML;
}

?>

<select name="height">
<?php echo createOptions($height_options, $_POST['height']); ?>
</select>

 

The above code will work if you follow psycos' advice and go with the decimal scheme, which will make your life much easier.

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.