尝试设置所选属性,代码最后有两个<option>元素

时间:2015-07-04 14:21:35

标签: jsp drop-down-menu jstl

我正在尝试在下拉列表中设置所选值。所以我这样做是通过比较选择选项的索引,如下,

<c:set var="questionids" value="Select Question,Employed?,Name?,Age (40+),Drinker?,Tobacco?,Smoker?" scope="application"/>
<select name="questionids" id="questionids" >
    <c:forEach items="${fn:split(questionids, ',')}" var="questionids" varStatus="loop">
        <c:if test="${healthWorkerQuestions == loop.index}" >
            <option value="${loop.index}" selected>${questionids}</option>
        </c:if>
        <c:if test="${healthWorkerQuestions != questionids}" >
            <option value="${loop.index}">${questionids}</option>
        </c:if>
    </c:forEach>
</select>

问题: 使用上面的代码,它比较索引并选择匹配的索引。随之而来的是它再次插入选项。

我不想再次插入选项。我只需要选择匹配的索引,不再需要插入。

那么我怎样才能设置匹配的索引而不再插入?

1 个答案:

答案 0 :(得分:0)

这是因为您要添加两次选项元素。您希望仅在<c:if test="${healthWorkerQuestions == loop.index}"属性上具有selected此条件。不是整个option代码

<c:set var="questionids" value="Select Question,Employed?,Name?,Age (40+),Drinker?,Tobacco?,Smoker?" scope="application"/>
       <select name="questionids" id="questionids" >
            <c:forEach items="${fn:split(questionids, ',')}" var="questionids" varStatus="loop">
                   <c:if test="${healthWorkerQuestions != questionids}" >            
                      <option value="${loop.index}" 
                       <c:if test="${healthWorkerQuestions == loop.index}" >selected</c:if>
                       >${questionids}</option>
                    </c:if>
           </c:forEach>
    </select>