Reputation: 827
I store Birthday Month in database as value using following code in JSP.
<select name="birthday_month" id="birthday_month">
<option value="-1">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
...
</select>
Output code in JSP to show previously selected item using JSTL that I am using (which is not correct)
<select name="birthday_month" id="birthday_month">
<c:forEach var="value" items="${birthdaymonth}">
<option value="${birthdaymonth}">${birthdaymonth}</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
...
</c:forEach>
</select>
What I am getting from this code is value like 1 or 2 in select tag
Other Information:
request.setAttribute("birthdaymonth", user.getBirthdayMonth());
What i was expecting
Upvotes: 2
Views: 25063
Reputation: 1108802
To dynamically iterate over a collection of months, you'd like to store the months in a Map<Integer, String>
where the key is the month number and the value is the month name. To make a HTML <option>
element by default selected, you need to set the selected
attribute.
So, assuming that you have a Map<Integer, String> months
and a Integer selectedMonth
in the scope, then the following should do:
<select name="birthday_month">
<c:forEach items="${months}" var="month">
<option value="${month.key}" ${month.key == selectedMonth ? 'selected' : ''}>${month.value}</option>
</c:forEach>
</select>
The conditional operator ?:
will print selected
when the selectedMonth
is equal to the currently iterated month number.
Upvotes: 7