Select option default based on database variable

2019-01-29 07:50发布

I have a form, with a simple select box, and I also have a text field that pulls a value. I want to use the value in $Defaultselection as the default value for the select options. So that if $Defaultselection = 4 then the default selected option would be D.

Using PHP/HTML

`$Defaultselection` 

contains an integer between 1-4.

<select >
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select> 

1条回答
聊天终结者
2楼-- · 2019-01-29 08:26

That should do it:

<select >
    <option value="1" <?php echo ($Defaultselection == 1)?"selected":""; ?>>A</option>
    <option value="2" <?php echo ($Defaultselection == 2)?"selected":""; ?>>B</option>
    <option value="3" <?php echo ($Defaultselection == 3)?"selected":""; ?>>C</option>
    <option value="4" <?php echo ($Defaultselection == 4)?"selected":""; ?>>D</option>
</select> 

or this other one:

<select >
    <option value="1" <?php if ($Defaultselection == 1) echo "selected"; ?>>A</option>
    <option value="2" <?php if ($Defaultselection == 2) echo "selected"; ?>>B</option>
    <option value="3" <?php if ($Defaultselection == 3) echo "selected"; ?>>C</option>
    <option value="4" <?php if ($Defaultselection == 4) echo "selected"; ?>>D</option>
</select> 
查看更多
登录 后发表回答