Search code examples
jspdrop-down-menujstl

Trying to set selected attribute, code ends up with two <option> elements


I am trying to set the selected value in drop down list. So I am doing this by comparing the indexes of the select options as follows,

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

Issue: With the above code it is comparing the index and selected the matched index. Along with that It is inserting the option again.

I don;t want to insert the option again. I just need to select the matched index and no insertion required again.

So how can I just set the matched index with out inserting again?


Solution

  • This is because you are adding option element twice. You want to have <c:if test="${healthWorkerQuestions == loop.index}" this condition only on selected attribute. Not on whole option tag

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