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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With