萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 重置按鈕清空表單數據的 jQuery 實作範例(補充版)

前言

本文補充說明 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 屬性(重置下拉選單)

兩大關鍵注意事項

  1. 清空邏輯的觸發元素(按鈕)不能放在 <form> 內:若置於表單內且為 type="reset",瀏覽器原生重置會先執行,導致 jQuery 清空邏輯失效或衝突。建議使用 type="button" 並置於表單外部,或以 event.preventDefault() 取消原生行為。
  2. 可直接寫在 onclick 屬性中:例如 <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 依賴,減少套件體積。

copyright © 萬盛學電腦網 all rights reserved