首页 > 解决方案 > 如何从复选框中获取值并将其传递给另一个 jsp 页面?

问题描述

我使用for循环创建了许多复选框。现在我想从复选框中获取值是否被勾选。

当一个复选框被勾选时,它的标签必须被传递到另一个 JSP 页面。但我无法正确实现它。

<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
</head>
    <body>
        <h1><center>REGISTER FORM</center></h1>
        <%
            String[] stArray=new String[40];
            ArrayList ar = new ArrayList();
            int idcounter = 0;
            try 
                {
                   Class.forName("com.mysql.jdbc.Driver");
                   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/registerdb", "root", "");
                   PreparedStatement ps = con.prepareStatement("select leave_types from leaves");
                   ResultSet rs = ps.executeQuery();

                   while(rs.next())
                   {
                        String array_value = rs.getString("leave_types");
                        ar.add(array_value);

                   }
                  // out.println(ar);
                   request.setAttribute("LEV_ARRAY", ar);
                }
                catch(Exception e)
                {
                    out.println(e);

                }


        %>
        <form action = "insertdata.jsp" name="myform" method="post">
        <%
                for(int i = 0; i<ar.size(); i++)
                {
                    out.println(ar.get(i));
            %>
                <input id ="<%=idcounter%>" type="checkbox" name = "" value="" /> 
            <%
                idcounter++;
                }
           //     String[] selectedCheckboxes = request.getParameterValues("selected");

            %>
 <center><button type= "submit" name="action">SIGN UP</button></center>
            </form>
 </body>
</html>

标签: mysqljspcheckbox

解决方案


你可以像下面这样:

ar.get(i)在复选框中作为值传递:

 <form action = "insertdata.jsp" name="myform" method="post">
        <%
                for(int i = 0; i<ar.size(); i++)
                {
                    out.println(ar.get(i));
         %>
    <!--name=abc will be used in jsp to get value selected in checkboxes-->
                <input id ="<%=idcounter%>" type="checkbox" name = "abc" value="<%=ar.get(i)%>" /> 
            <%
                idcounter++;
                }
           %>
 <center><input type= "submit" name="action" value="SIGN UP"/></center>
            </form>

然后,要达到上面values的要求,jsp page请执行以下操作:

 <!--getting values selected using "abc"-->
     <%String check[]= request.getParameterValues("abc");
    <!--checking for null values-->
            if(check!= null){%>
    <!--there might be more one checkbox selected so, using loop-->    
      <%for(int i=0; i<check.length; i++){%>
     <!--printing values selected-->
                <%=check[i]%> 
               <%}
           }%>  

推荐阅读