使用 PHP 变量初始化选择标签



我有一个选择标签...

<select id="input_O6" type="text" name="select_input">
        <option value="Level 1">Level 1</option>
        <option value="Level 2">Level 2</option>
        <option value="Level 3">Level 3</option>
        <option value="Level 4">Level 4</option>
        <option value="Level 5">Level 5</option>
        <option value="Level 6">Level 6</option>
        <option value="Level 7">Level 7</option>
        <option value="Level 8">Level 8</option>
        </select>

用户选择一个值,我将所选值存储到 sql 数据库中。当我重新加载页面时,我正在检索在我的 php 中选择的值,并尝试将 select 标签设置为此值。其他输入,我只是这样做...

<input id="input_O3" type="number" value=<?php echo $storedValue_O3;?>>

有没有一种简单的方法可以为选择标签执行此操作?

提前致谢

for($i = 1; $i<=8; $i++){
  $selected = ($storedValue_O3 == $i) ? "selected" : null;
  echo "<option value='Level ".$i."' ".$selected.">Level ".$i."</option> ";
}

选项字段具有selected属性。您可以使用 php 进行设置:

<select id="input_O6" type="text" name="select_input">
    <option value="Level 1" <?php echo ($selectedval == 1 ? 'selected' : '') ?>>Level 1</option>
    <option value="Level 2" <?php echo ($selectedval == 2 ? 'selected' : '') ?>>Level 2</option>
    <option value="Level 3" <?php echo ($selectedval == 3 ? 'selected' : '') ?>>Level 3</option>
    <option value="Level 4" <?php echo ($selectedval == 4 ? 'selected' : '') ?>>Level 4</option>
</select>

$_POST$_GET获取输入变量,具体取决于表单提交方法。

获取数组中的所有下拉选项,遍历它们。

并创建选项。

如果获取所选值,请将特定option选中,否则不选中。

这应该有效。

<?php
$select_input = ! empty($_POST['select_input']) ? $_POST['select_input'] : '';

获取输入变量:

?>

并执行以下操作更改:

<?php
$select_input = ! empty($_POST['select_input']) ? $_POST['select_input'] : '';
$arrInp = array();
$arrInp['Level 1'] = 'Level 1';
$arrInp['Level 2'] = 'Level 2';
$arrInp['Level 3'] = 'Level 3';
$arrInp['Level 4'] = 'Level 4';
$arrInp['Level 5'] = 'Level 5';
$arrInp['Level 6'] = 'Level 6';
$arrInp['Level 7'] = 'Level 7';
$arrInp['Level 8'] = 'Level 8';
?>

<select id="input_O6" type="text" name="select_input">
    <?php
    foreach ($arrInp as $k => $v) {
        $selected = ($select_input == $k) ? 'selected="selected"' : '';
    ?>
        <option value="<?php echo $k;?>" <?php echo $selected;?>><?php echo $v;?></option>
        <?php
 } 
       ?>
</select>

最新更新