Home > Net >  Pre Select an Option in a form based on variable?
Pre Select an Option in a form based on variable?

Time:06-25

<select name="radio_typ" id="radio_typ" >
    <option value="P5100">P5100</option>
    <option value="P5400">P5400</option>
    <option value="P7100">P7100</option>
    <option value="P7200">P7200</option>
    <option value="700P">Jaguar 700p</option>
    <option value="LPE200">LPE200</option>
    <option value="XL200">XL200</option>
</select>

I'd like to be able to pre-select an option in a drop down menu based on a variable from a database which will already be set to the current setting. This form is for the purpose of editing the setting if needbe.

I tried inserting value="<?php echo $radio_typ;?> but that didn't seem to work.

Any hints as to how I could do this?

CodePudding user response:

Thank you twofed.

That code didn't quite work, but I was able to figure out a solution that did based on that thought process.

<select name="radio_typ" id="radio_typ" >
    <?php foreach ($options as $value => $name) { 
        if ($value == $radio_typ) {
        $sel = "selected";
        } else {
        $sel = "";
        }?>
        <option value="<?= $value; ?>" <?= $sel; ?>><?= $name; ?></option>
    <?php } ?>
</select>

CodePudding user response:

I think, the best solution would be:

<?php

$radio_typ = "700P";

// value => name
$options = [
    "P5100" => "P5100",
    "P5400" => "P5400",
    "P7100" => "P7100",
    "P7200" => "P7200",
    "700P" => "Jaguar 700p",
    "LPE200" => "LPE200",
    "XL200" => "XL200"
];

?>

<select name="radio_typ" id="radio_typ" >
    <?php foreach ($options as $value => $name) { ?>
        <option value="<?= $value; ?>" <?= ($value !== $radio_typ) ?: "selected"; ?>><?= $name; ?></option>
    <?php } ?>
</select>
  • Related