Set selected option on existing select tag with jstl

橙三吉。 提交于 2019-12-18 16:09:12

问题


So I have a select for the grade on each subject. It's predefined and hence I don't have to store grades as a table in the database. I have a list of qualifications and I using jstl for each like this: <c:forEach items="${qualificationdetails}" var="qd">.

For each item I am producing a select like this.

<select class="grade" title="Grade Obtained">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="A">A</option>
   <option value="B">B</option>
   <option value="C">C</option>
   <option value="D">D</option>
   <option value="E">E</option>
</select>

Is it possible to set the selected option using my variable qd ? something like

<option value="${qd.grade}" selected="selecetd">${qd.grade}</option>

This will add a duplicate option to the select. I think it would a bit "clunky" to make an array with the grades and send it accross for generating the options. Any ideas ?


回答1:


You could just let JSP render the selected attribute conditionally.

<select class="grade" title="Grade Obtained">
    <option value="1" ${qd.grade == '1' ? 'selected' : ''}>1</option>
    <option value="2" ${qd.grade == '2' ? 'selected' : ''}>2</option>
    <option value="3" ${qd.grade == '3' ? 'selected' : ''}>3</option>
    <option value="A" ${qd.grade == 'A' ? 'selected' : ''}>A</option>
    <option value="B" ${qd.grade == 'B' ? 'selected' : ''}>B</option>
    <option value="C" ${qd.grade == 'C' ? 'selected' : ''}>C</option>
    <option value="D" ${qd.grade == 'D' ? 'selected' : ''}>D</option>
    <option value="E" ${qd.grade == 'E' ? 'selected' : ''}>E</option>
</select>

Alternatively, you could just create a collection/array of grades and store it in the application scope so that it's available in EL so that you can loop over it using <c:forEach>. I'm not sure how that would be "clunky". You could use <c:set> to store them commaseparated and use fn:split() to split them for <c:forEach>.

<c:set var="grades" value="1,2,3,A,B,C,D,E" scope="application" />
<select class="grade" title="Grade Obtained">
    <c:forEach items="${fn:split(grades, ',')}" var="grade">
        <option value="${grade}" ${qd.grade == grade ? 'selected' : ''}>${grade}</option>
    </c:forEach>
</select>

This way you end up with more DRY code.



来源:https://stackoverflow.com/questions/12008698/set-selected-option-on-existing-select-tag-with-jstl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!