下拉选择=“已选中”问题

时间:2016-10-02 15:38:04

标签: php

我正在用PHP构建学校脚本。我的PHP代码片段是这样的:

$sid = intval($mybb->input['sid']);
$query = $db->simple_select("student_list", "*", "sid='{$sid}'");
$s = $db->fetch_array($query);

$class_selected = '';
if ($s['student_class'] == $mybb->input['student_class'])
{
    $class_selected = ' selected="selected"';
}

和HTML是这样的:

<select name="student_class" class="textbox" tabindex="2">
    <option value="Play Group"'.$class_selected.'>Play Group</option>
    <option value="Nursery"'.$class_selected.'>Nursery</option>
    <option value="Prep."'.$class_selected.'>Prep.</option>
    <option value="1"'.$class_selected.'>One</option>
    <option value="2"'.$class_selected.'>Two</option>
    <option value="3"'.$class_selected.'>Three</option>
    <option value="4"'.$class_selected.'>Four</option>
    <option value="5"'.$class_selected.'>Five</option>
    <option value="6"'.$class_selected.'>Six</option>
    <option value="7"'.$class_selected.'>Seven</option>
    <option value="8"'.$class_selected.'>Eight</option>
    <option value="9"'.$class_selected.'>Nine</option>
    <option value="10"'.$class_selected.'>Ten</option>
</select>

但遗憾的是,在运行脚本时,根本没有选择该值。 :/

顺便说一下,$s['student_class']的值为Nursery

请帮忙。

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说,最好使用三元运算符来做这样的事情。

  • 他们在回声中有点棘手,但值得付出努力。

假设查询成功并且:

if ($s['student_class'] == $mybb->input['student_class'])

以上等于下面的选项之一并记住字符串区分大小写,以下内容将起作用:

旁注:您在评论中提到代码在回声中。

$class_selected = 'Nursery'; // Assumed input

echo '
<select name="student_class" class="textbox" tabindex="2">

    <option value="Play Group" '.(($class_selected == 'Play Group') ? "selected" : "").'>Play Group</option>

    <option value="Nursery" '.(($class_selected == 'Nursery') ? "selected" : "").'>Nursery</option>

    <option value="" '.(($class_selected == 'Prep.') ? "selected" : "").'>Prep.</option>

    <option value="1" '.(($class_selected == '1') ? "selected" : "").'>One</option>

    <option value="2" '.(($class_selected == '2') ? "selected" : "").'>Two</option>

    <option value="3" '.(($class_selected == '3') ? "selected" : "").'>Three</option>

    <option value="4" '.(($class_selected == '4') ? "selected" : "").'>Four</option>

    <option value="5" '.(($class_selected == '5') ? "selected" : "").'>Five</option>

    <option value="6" '.(($class_selected == '6') ? "selected" : "").'>Six</option>

    <option value="7" '.(($class_selected == '7') ? "selected" : "").'>Seven</option>

    <option value="8" '.(($class_selected == '8') ? "selected" : "").'>Eight</option>

    <option value="9" '.(($class_selected == '9') ? "selected" : "").'>Nine</option>

    <option value="10" '.(($class_selected == '10') ? "selected" : "").'>Ten</option>

</select>

';