在php中设置select输入的默认值

时间:2017-08-21 08:10:25

标签: php

我想将默认值设置为“-24hours”。所有选项都是使用foreach动态生成的。

<select id="search3" name="date" onchange='this.form.submit();'>
    <?php
        $orderby_options3 = array(
            '-3day' => 'Last 3 days',
            '-48hours' => '48 hours',
            '-24hours' => '24 hours',
        );
        foreach( $orderby_options3 as $value3 => $label3 ) {
            echo "<option ".selected( $_GET['date'], $value3 )." value='$value3'>$label3</option>";
        }
    ?>
</select>

我知道我应该为选项添加“selected”参数但在我的情况下,这是不可能的。

2 个答案:

答案 0 :(得分:0)

试试这个:

<select id="search3" name="date" onchange='this.form.submit();'>
    <?php
        $orderby_options3 = array(
            '-3day' => 'Last 3 days',
            '-48hours' => '48 hours',
            '-24hours' => '24 hours',
        );
        foreach( $orderby_options3 as $value3 => $label3 ) {
            $selected = in_array($value3, [$_GET['date'] ?? null, '-24hours']) ? 'selected' : '';
            echo "<option $selected value='$value3'>$label3</option>";
        }
    ?>
</select>

click to see the demo

答案 1 :(得分:0)

如果您总是希望选择-24小时并且此页面不会用作编辑页面,那么您可以执行以下操作:

<select id="search3" name="date" onchange='this.form.submit();'>
<?php
    $orderby_options3 = array(
        '-3day' => 'Last 3 days',
        '-48hours' => '48 hours',
        '-24hours' => '24 hours',
    );

    foreach( $orderby_options3 as $value3 => $label3 ) {
        $select = ($value3 == '-24hours') ? "selected='selected'":""; // see this line
        echo "<option ".selected( $_GET['date'], $value3 )." value='$value3' $select>$label3</option>";
    }
?>