JSP how to include a select within a checkbox

Asked

Viewed 634 times

0

I am developing a web application, with java spring mvc, and need to list items in a dynamic checkboxList and include a select option in each item.

Something that in html would be similar to the code below:

<ul>
    <li>
        <input type="checkbox"> Item 1 - 
            <select>
                <option value="1">Ativo</option>
                <option value="2">Inativo</option>
                <option value="3">Bloqueado</option>
            </select>
    </li>
    <li>
        <input type="checkbox"> Item 2 - 
            <select>
                <option value="1">Ativo</option>
                <option value="2">Inativo</option>
                <option value="3">Bloqueado</option>
            </select>
    </li>
    <li>
        <input type="checkbox"> Item 3 - 
            <select>
                <option value="1">Ativo</option>
                <option value="2">Inativo</option>
                <option value="3">Bloqueado</option>
            </select>
    </li>
</ul>

How can I do this dynamically in jsp? Remembering that the checkbox items come from the database.

2 answers

1

This is Erico. Everything ?

Well, in a JSP page you can use the opening and closing tags of java code within a JSP page. EX:

            <select>
                <%
                   List<String> resultado = ClasseDAO.pegarResultado();
                   for(String valor : resultado ){
                     out.println("<option value=\"" + valor + "\" >" + valor  + "</option>");
                   }
                 %>
            </select>
  • Man, thank you, your answer helps and solves quickly, but if we follow good practices, it’s not very nice to put java code in the jsp, let alone invoke a DAO class. But as I’m kind of starting in the jsp, knowing this feature is already a big help.

1


If you are using JSP with JSTL, include at the beginning of the file:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

And in every place you need the select, put

<select>
<c:forEach var="item" items="${algumBean.listaDeAlgumaCoisa}">
  <option value="${fn:escapeXml(item.valor)}">${fn:escapeXml(item.descricao)}</option>
</c:forEach>
</select>

listaDeAlgumaCoisashould be a list of objects where each contains a field called valor and a field called descricao. How to make the object algumBean available to the page depends a little on the framework, and I’ve never done any projects with Spring, but it shouldn’t be difficult.

Remembering that with Java and Spring it is possible to use several template languages, as JSP (with JSTL and also others tag libraries), Thymeleaf, Freemarker, etc. Since your example is in pure HTML, I couldn’t check what you’re using, I did the example using only JSP with JSTL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.