我們在提交 form 的時候用了多種 input 表單,可是不是每一種 input 都很簡單地用 document.getElementById 就能取到。像 checkbox、radio、select 這種「一組」的欄位,前端與伺服器端的讀法各不相同。多說無用,上程式碼。
<form action="input.do" name="formkk">
<table>
<tbody>
<tr>
<td>text:</td>
<td><input type="text" name="text"></td>
</tr>
<tr>
<td>password:</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td>radio:</td>
<td>
<input type="radio" name="xingbie" value="1"> 男
<input type="radio" name="xingbie" value="2"> 女
</td>
</tr>
<tr>
<td>checkbox:</td>
<td>
足球:<input type="checkbox" name="hobby" value="1" />
籃球:<input type="checkbox" name="hobby" value="2" />
拍球:<input type="checkbox" name="hobby" value="3" />
斗球:<input type="checkbox" name="hobby" value="4" />
</td>
</tr>
<tr>
<td>hidden:</td>
<td><input type="hidden" value="123" name="hidden" /></td>
</tr>
<tr>
<td>option:</td>
<td>
<select name="opt" id="opt">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="button" value="提交" onclick="javascript:check()" />
</form>
function check() {
var radio = document.getElementsByName("xingbie");
var checkbox = document.getElementsByName("hobby");
var select = document.getElementById("opt"); // 取得 select 標籤
// 取得 select 標籤的選中項
var index = select.selectedIndex;
var text = select.options[index].text;
var value = select.options[index].value;
// 取得 radio 標籤(單選,找到第一個 checked 即可)
for (var i = 0; i < radio.length; i++) {
if (radio.item(i).checked) {
var val = radio.item(i).getAttribute("value");
break;
}
continue;
}
// 取得 checkbox 標籤(多選,必須跑完整個迴圈)
for (var j = 0; j < checkbox.length; j++) {
if (checkbox[j].checked) {
alert(checkbox[j].value);
}
continue;
}
// 提交 form 表單
document.formkk.submit();
}
三者的重點各異:select 靠 selectedIndex 定位;radio 是單選,找到第一個 checked 就 break;checkbox 是多選,必須完整跑完迴圈收集所有勾選項。
String[] hobbys = request.getParameterValues("hobby"); // checkbox → 陣列
String text = request.getParameter("text"); // text
String password = request.getParameter("password"); // password
String xingbie = request.getParameter("xingbie"); // radio → 單值
request.getParameter("hidden"); // hidden
request.getParameter("opt"); // select
最關鍵的差異是:多選欄位一定要用 getParameterValues() 取陣列,用 getParameter() 只會拿到第一個值。另外別忘了前端若以 GET 送中文,後端記得指定 request.setCharacterEncoding("UTF-8"),否則一樣會亂碼。