介紹兩種取得checkbox的方法
在找資料前我都是用第一種方法,
第二種方法,也是蠻方便的
1.使用checkbox來收集資料
=== check.html ===
<HTML>
<title>Check Fruit</title>
<BODY bgcolor="white">
<FORM method=POST ACTION=checkresult.jsp>
<BR>
<font size=5 color="red">
Check all Favorite fruits: <br>
<input TYPE=checkbox name=fruit VALUE=apples> Apples <BR>
<input TYPE=checkbox name=fruit VALUE=grapes> Grapes <BR>
<input TYPE=checkbox name=fruit VALUE=oranges> Oranges <BR>
<input TYPE=checkbox name=fruit VALUE=melons> Melons <BR>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</font>
</FORM>
</BODY>
</HTML>
2.一個水果的集合
=== CheckTest.java===
package demo;
public class CheckTest {
String b[] = new String[]{"1", "2", "3", "4"};
public String[] getFruit() {
return b;
}
public void setFruit(String[] b) {
this.b = b;
}
}
3.第一種方法是直接透過request.getParameterValues
而checkbox 的值回傳是一個array
第二種方法是使用Bean來收資料,在Bean裡面定義array
=== checkresult.jsp ===
<title>Check Result</title>
<body bgcolor="white"><hr>
<%! String[] fruits;%>
<jsp:useBean id="foo" scope="page" class="demo.CheckTest" />
<jsp:setProperty name="foo" property="fruit" param="fruit" />
Check Result
The checked fruits (got using request) are: <br>
<%
fruits = request.getParameterValues("fruit");
%>
<ul>
<%
if (fruits != null) {
for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
out.println(fruits[i]);
}
} else
out.println("none selected");
%>
</ul>
<br>
<hr>
The checked fruits (got using beans) are <br>
<%
fruits = foo.getFruit();
%>
<ul>
<%
if (!fruits[0].equals("1")) {
for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
out.println(fruits[i]);
}
} else
out.println("none selected");
%>
</ul>