How can I pre-populate a HTML radio button using JSP, depending on the value in the database?
Asked
Active
Viewed 8,186 times
2 Answers
8
You just need to let JSP print the checked
attribute of the HTML <input type="radio">
element. Easiest way to do that is using the conditional operator ?:
in EL. Here's a kickoff example:
<input type="radio" name="foo" value="one" ${bean.foo == 'one' ? 'checked' : ''}/>
<input type="radio" name="foo" value="two" ${bean.foo == 'two' ? 'checked' : ''}/>
...
Or if you have all available input values in some collection like List<String>
, then do:
<c:forEach items="${foos}" var="foo">
<input type="radio" name="foo" value="${foo}" ${bean.foo == foo ? 'checked' : ''}/>
</c:forEach>
Either way, it should ultimately end up as follows in the generated HTML if ${bean.foo}
equals to "two"
:
<input type="radio" name="foo" value="one" />
<input type="radio" name="foo" value="two" checked />
...
See also:

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
Excellent, thanks again BalusC - I will take this away and use these examples! Appreciate your help. – Gary Deuces Rozanski Nov 15 '11 at 18:05
-
Hey BalusC, in the second example you provided could you just give me a heads up on what the difference is between ${foos} and ${foo} I don't think I understand beans & foos enough to be able to follow your examples. – Gary Deuces Rozanski Nov 15 '11 at 19:50
-
The `${foos}` is the collection. The `${foo}` is the currently iterated item. See also http://stackoverflow.com/questions/1727603/places-where-java-beans-used, http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files and http://stackoverflow.com/tags/servlets/info – BalusC Nov 15 '11 at 19:52
1
Pure JSP Scriplets
<input type="radio" name="gender" value="male" <% if (resultSet.getString("gender").equals("male")) out.print("checked"); else out.print(""); %> />
<input type="radio" name="gender" value="female" <% if (resultSet.getString("gender").equals("female")) out.print("checked"); else out.print(""); %> />

antelove
- 3,216
- 26
- 20