Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-populating radio buttons in JSP

How can I pre-populate a HTML radio button using JSP, depending on the value in the database?

like image 862
Gary Deuces Rozanski Avatar asked Nov 15 '11 17:11

Gary Deuces Rozanski


2 Answers

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:

  • How can I retain HTML form field values in JSP after submitting form to Servlet?
like image 136
BalusC Avatar answered Oct 22 '22 23:10

BalusC


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(""); %> />
like image 27
antelove Avatar answered Oct 22 '22 22:10

antelove