本文補充說明 JSP 表單重置按鈕如何清空包含後端傳入初始值的表單欄位。原生 <input type="reset"> 僅能恢復到頁面載入時的狀態,無法清除後端綁定的預設值,需透過 jQuery 手動清空。
$(':input', '#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
| 鏈式方法 | 作用 |
|---|---|
$(':input', '#myform') | 選取 id 為 myform 的表單內所有輸入類元素(input、select、textarea 等) |
.not(':button, :submit, :reset, :hidden') | 排除功能性按鈕與隱藏欄位,避免誤清除 |
.val('') | 將文字、密碼、下拉選單、文字域的 value 設為空字串 |
.removeAttr('checked') | 移除 checkbox、radio 的 checked 屬性(取消勾選) |
.removeAttr('selected') | 移除 select option 的 selected 屬性(重置下拉選單) |
<form> 內:若置於表單內且為 type="reset",瀏覽器原生重置會先執行,導致 jQuery 清空邏輯失效或衝突。建議使用 type="button" 並置於表單外部,或以 event.preventDefault() 取消原生行為。<input type="button" value="清空" onclick="clearForm()">,並在 script 定義 clearForm() 封裝上述鏈式呼叫。<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
function clearForm() {
$(':input', '#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
</script>
</head>
<body>
<form id="myform" action="/submit" method="post">
<input type="text" name="username" value="後端傳入的預設值"><br>
<input type="checkbox" name="agree" checked> 同意條款<br>
<select name="city">
<option value="tp" selected>台北</option>
<option value="kc">高雄</option>
</select><br>
</form>
<!-- 清空按鈕置於 form 外部 -->
<input type="button" value="重置表單" onclick="clearForm()">
</body>
</html>
若專案使用 ES6+ 或前端框架,建議改用原生 form.reset() 搭配手動遍歷 form.elements 清空 value、checked、selectedIndex,移除 jQuery 依賴,減少套件體積。