Reputation: 121
Ok. I'm making a java web app with a database backend to do some CRUD on some data. When the edit button is clicked next to an item, it navigates to a form with the current data for editing. One of the fields is boolean and I would like to display it as a checkbox so that True
makes it checked and False
leaves it unchecked.
I have tried many different variations none seem to work. Here are some examples where <%= action.get("stable")%>
returns a string with either True
or False
<input TYPE=checkbox name="stable" value=<%= action.get("stable") %>
<input TYPE=checkbox name="stable" value=<%= action.get("stable")?"True":"False" %><%= action.get("stable")?"checked":"" %>
<input TYPE=checkbox name="stable" checked=<%= action.get("stable")%>/>
So how do you set a check box to checked/unchecked depending on the string returned with action.get("stable")
Thank you for any help sorry if the question is a bit trivial.
Upvotes: 2
Views: 41178
Reputation: 961
I used this, and it worked perfectly.
<input type="checkbox" <c:if test="${item.estado==2}">checked=checked</c:if> class="switch-input" >
Upvotes: 5
Reputation: 94645
You need to set checked
attribute of <input type="checkbox"/>
Edit:
<input type="checkbox" <%=action.get("stable") ? "checked='checked'" : "" %> />
Upvotes: 1
Reputation: 691755
The correct markup for a checked checkbox is checked="checked"
. If it's not checked, the checked
attribute must not be present at all.
You should generate it using the JSTL and the JSP EL, because scriptlets are something from the past which should not be used in JSPs for years. See How to avoid Java code in JSP files?.
This would of course need some refactoring so that the action bean has a regular isStable()
method returning a boolean, which would be much cleaner. But anyway, here's how it would work using your existing code :
<input type="checkbox" name="stable" <%
if ("True".equals(action.get("stable"))) {
out.print("checked=\"checked\"");
} %>/>
Note that all attributes should also be surrounded by quotes.
Upvotes: 3