0

I am basically looping through an Arraylist in a JSP page and I can successfully populate a Dropdown with options.

<select id="perm_bmi_stable" name="perm_bmi_stable" class="col-md-12 form-control">
    <optgroup label="Stability">
        <c:forEach items="${versions}" var="version">
            <option value="${version.versionName}"> ${version.versionName </option>
        </c:forEach>
    </optgroup>
</select>

Now I need to set the proper value in the dropdown as selected depending on the value of the version.versionName value.

The Dropdown contains the following values after the for loop generates them:

  • 1.0
  • 2.0
  • 3.0
  • 4.0

If the value in the version.versionName is for example 2.0, I need the loop to set 2.0 as the dropdown's selected option.

How can I add this if condition to my for loop?

I tried this, But it doesn't work:

<option value="${version.versionName}" <c:if test="${versions[0].versionName == '${version.versionName}'}"> <c:out value="selected=selected"></c:out></c:if>>${version.versionName}</option>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Jay
  • 4,873
  • 7
  • 72
  • 137

2 Answers2

1

It doesn't work because you are not using expression language properly

${....} contains EL expressions not EL variables and variables unlike String literals do not need quotes inside EL expressions

Therefore this will not work

<option value="${version.versionName}" <c:if test="${versions[0].versionName == '${version.versionName}'}"> <c:out value="selected=selected"></c:out></c:if>>${version.versionName}</option>

This should work. Note: you might want to add quotes around the selected attribute to have a consistent notation

<option value="${version.versionName}" <c:if test="${versions[0].versionName == version.versionName}"> <c:out value='selected="selected"'></c:out></c:if>>${version.versionName}</option>

To improve readability you might want to get rid of the c:out tags if they are not strictly necessary and use the ternary operator

Note: in this case, if you want double quotes around the selected attribute you can create a var to use inside the EL expression not to create conflict between quotes

<c:set var="sel" value='selected = "selected"'>

<option value="${version.versionName}" "${versions[0].versionName == version.versionName ? sel : ''}"> ${version.versionName}</option>
Angelo Oparah
  • 673
  • 1
  • 7
  • 18
0

Have a try with the help of Ternary operator

 <option value="${version.versionName}" ${versions[0].versionName == version.versionName?'selected=selected':''} >${version.versionName}</option>
Niju
  • 487
  • 1
  • 9
  • 18