简体   繁体   中英

Setting jsp checkbox with a value from database

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.

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.

You need to set checked attribute of <input type="checkbox"/>

Edit:

<input type="checkbox" <%=action.get("stable") ? "checked='checked'" : "" %> />

我使用了它,并且效果很好。

 <input type="checkbox" <c:if test="${item.estado==2}">checked=checked</c:if> class="switch-input" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM