Frage

After referring to the post

Set HTML dropdown selected option using JSTL

I have written a JSP in the following way.

<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>

But when the option is selected a servlet is called and the servlet puts an attribute called level into the JSP redirects to the same page. When level is not null I see only hard option in the dropdown list irrespective of the selected option i.e. easy, or medium, or hard. Any guidance is greatly appreciated.

War es hilfreich?

Lösung

AFAIK that code will generate invalid HTML. Your <select> allows a single option being selected, not multiple. So, change the code for selection in <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>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top