I’m creating a time entry system where the user has the option of selecting the hour and minute via two separate drop down select boxes. So the hour box has the numbers 1-12 in it, and the minute box has 00-59.
This is part of a Spring 2.5 Java EE project.
I have this in my JSP, for example, to create the option values as part of a select dropdown list:
<% for( int i=1; i<=12; i++) { %>
<option value="<%=i %>" <%= Integer.parseInt(time1fromHr)==i?selected:"" %> />
<% } %>
The for loop generates all the hours and marks the currently selected hour as default. Well, it looks pretty ugly to me, mostly because there is quite a bit of Java code involved here and I was wondering if there is a more elegant solution to approaching this problem using JSP tags or the Spring library. I am passing in the currently set parameters via the ModelAndView object in Spring.
In your model you could pass a List of Integers for hours, and another for minutes. Then you could use the form:select tag.
If your command object for the form has the selected value set in the “hour” value, and the model contains 1-12 in the “hours” value, then it should render the select and take care of marking the appropriate option selected. Then you do the same for minutes.
If you don’t want to go the spring form taglib direction, you could again place the hours in the model and use JSTL. Something like:
I know there’s a better way to do the c:if part, maybe using a c:choose, but you get the gist. You have your selected value in selectedHour and your choices in hours in the model.