无法设置选中的HTML下拉选项

时间:2014-05-11 06:56:24

标签: html jsp servlets

参考帖子后

Set HTML dropdown selected option using JSTL

我已按以下方式撰写JSP

<form name="options" id="options" action="${pageContext.request.contextPath}/difficulty.do" method="post">
        <div id="difficulty">
            <label style="font-weight: bold; color: gray; margin-left: 16px">Difficulty Level</label><br>
            <select name="difficultyLevel" style="color: gray; margin-top: 5px" onchange="optionChanged()">
                <c:if test="${level == null}">
                    <option value="easy" name="easy" selected>Easy</option>
                    <option value="medium" name="medium">Medium</option>
                    <option value="hard" name="hard">Hard</option>
                </c:if>
                <c:if test="${level != null}">
                    <option value="easy" name="easy" selected=${level == 'easy' ? "selected" : ''}>Easy</option>
                    <option value="medium" name="medium" selected=${level == 'medium' ? "selected" : ''}>Medium</option>
                    <option value="hard" name="hard" selected=${level == 'hard' ? "selected" : ''}>Hard</option>
                </c:if>
            </select>
        </div>
    </form>
    <script type="text/javascript">
        $('select').on({ "focus": function () {
        this.selectedIndex = -1;
    }, "change": function () {
        $('#options').submit();
    }
    });
    </script>
</form>

但是当选择该选项时,将调用一个servlet,并且servlet将一个名为level的属性放入JSP重定向到同一页面。当levelnot null时,hard只会dropdown list选项easy, or medium, or hard,无论选择的选项是{{1}}。非常感谢任何指导。

1 个答案:

答案 0 :(得分:0)

AFAIK该代码将生成无效的HTML。您的<select>允许选择一个选项,而不是多个选项。因此,请更改<option>中的选择代码:

<option value="easy" name="easy" ${level == 'easy' ? "selected" : ''}>Easy</option>
<option value="medium" name="medium" ${level == 'medium' ? "selected" : ''}>Medium</option>
<option value="hard" name="hard" ${level == 'hard' ? "selected" : ''}>Hard</option>