JavaBean专题

获取选中复选框里的数据

2018-08-18  本文已影响0人  神坛下的我

StringUtil.java

public class StringUtil4 {
    private String str;//要分割的字符串
    @SuppressWarnings("unused")
    private String strArr[];
    private String listSeparator;//分隔符号
    public StringUtil4(){}
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }
    public String[] getStrArr() {
        return str.split(listSeparator);
    }
    public String getListSeparator() {
        return listSeparator;
    }
    public void setListSeparator(String listSeparator) {
        this.listSeparator = listSeparator;
    }
}

index.jsp

<body>
    <script type="text/javascript">
        function a(){
            var checkObj = document.getElementsByName("like");
            //var likeStr="";
            for(var i=0;i<checkObj.length;i++){
                if(checkObj[i].checked){
                    document.getElementById("likes").value+=checkObj[i].value+",";
                }
            }
            //将组合后复选框的内容赋给隐藏域
            //document.getElementById("likes").value=likeStr;
            
        }
    </script>
    
    <form name="form" action="result.jsp" method="post">
        <input type="hidden" name="likes" id="likes"/>
        <table width="220">
            <tr bgcolor="skyblue"><td align="center">您喜欢的运动有:</td></tr>
            <tr>
            <td>
                <input type="checkbox" name="like" value="打篮球">打篮球
                <input type="checkbox" name="like" value="踢足球">踢足球
                <input type="checkbox" name="like" value="打乒乓球">打乒乓球
                <input type="checkbox" name="like" value="跑步">跑步
                <input type="checkbox" name="like" value="打羽毛球">羽毛球
                <input type="checkbox" name="like" value="游泳">游泳
            </td>
            </tr>
            <tr bgcolor="skyblue">
                <td align="center">
                    <input type="submit" value="提交" onclick="a()"/>
                    </td>
                    </tr>
        </table>

    
    </form>

</body>

result.jsp

<body>
    <%
        request.setCharacterEncoding("utf-8");
        String likes=request.getParameter("likes");/*从请求中获取分隔的字符串*/
    %>
    <jsp:useBean id="strBean" class="com.count.StringUtil4"></jsp:useBean>
    <!-- 对StringUtil类的对象strBean的str属性赋值 -->
    <jsp:setProperty property="str" name="strBean" value="<%=likes %>"/>
    <!-- 对listSeparator属性赋值 -->
    <jsp:setProperty property="listSeparator" name="strBean" value=","/>
    <%
        String[] likeArr = strBean.getStrArr();
    %>
    <table>
        <tr>
            <td width="100" valign="top">您选择的运动有:</td>
            <%
                for(String s:likeArr){
            %>
            <td align="left">【<%=s %>】</td>
            <%} %>
        </tr>
    </table>
</body>
3.PNG 4.PNG 5.PNG
上一篇下一篇

猜你喜欢

热点阅读