如何使用 jQuery 和 Web Storage API 自動填充表單?


透過自動填充姓名、電子郵件和地址等常用欄位,自動填充表單作為網站和移動應用程式的一項功能越來越受歡迎。在開發自動填充表單時,開發者有兩個選擇:要麼使用本地儲存的固定資料,要麼使用根據使用者輸入定期更新的動態資料。

Web Storage API 是開發者可用的最重要的本地資料儲存資源之一。它提供了比使用 Cookie 更自然的方式讓瀏覽器儲存鍵值對的方法。sessionStorage 和 localStorage 是兩種 Web Storage 技術;sessionStorage 只在會話期間或關閉瀏覽器之前保留資料,而 localStorage 即使在關閉瀏覽器並重新開啟後也能保留資料。因此,建議使用 localStorage 來自動填充表單。

在本文中,我們將研究使用 Web Storage API 構建自動填充表單的兩種不同方法。第一種方法涉及使用 window.localStorage.setItem(key, value) 來本地儲存固定資料,這些資料稍後在指令碼標籤中檢索並用於自動填充表單。第二種策略涉及儲存輸入。

方法

要使用 JQuery 和 Web Storage API 建立自動填充表單,我們可以遵循兩種方法:

  • 利用本地固定資料。

  • 利用動態儲存的資料。

讓我們看看這兩種方法:

方法 1:利用本地固定資料

這種方法執行一些簡單的前端使用者互動,將一些資料傳輸到伺服器,並允許使用者刪除任何先前儲存的資料。

演算法

執行此程式碼的步驟如下:

  • 步驟 1 - 在陣列中構建水果名稱。

  • 步驟 2 - 使用水果陣列和水果輸入欄位建立自動完成小部件。

  • 步驟 3 - 當用戶在輸入欄位中輸入水果名稱時,自動填充小部件會嘗試選擇正確的選項進行自動填充。

  • 步驟 4 - 提交水果名稱併發送到伺服器。

示例

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Form</title>
   <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
   <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
   <link  href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">
   <script>
      $(function() {
         var fruits = ["Persimmon", "Tangerine","Kumquat", "Clementine", "Grapefruit", "Blood orange","Dragonfruit", "Fig", "Date", "Coconut", "Avocado", "Pineapple", "Passionfruit", "Watermelon", "Honeydew", "Cantaloupe", "Jackfruit", "Lychee", "Mangosteen","Apple", "Banana", "Orange", "Mango", "Pineapple", "Kiwi", "Lemon", "Lime", "Grapefruit", "Grapes", "Strawberry", "Blueberry", "Raspberry", "Blackberry", "Cranberry", "Pomegranate", "Cherry", "Apricot", "Peach", "Plum", "Pear", "Quince", "Guava", "Papaya",  "Starfruit", "Tangelo", "Ugli fruit", "Kiwi fruit", "Mulberry", "Blackcurrant", "Redcurrant", "Goji berry", "Acai berry", "Cactus pear", "Feijoa", "Nectarine", "Soursop", "Cranberry", "Tamarind", "Yuzu", "Cherimoya"];
         $("#input_fruit").autocomplete({
            source: fruits
         });
         $("#clear").click(function(){
            localStorage.clear();
         });
      });
   </script>
</head>
<body>
   <h2>Form</h2>
   <form id="submitted" name="submitted">
      <label for="input_fruit">Enter Fruit:</label>
      <input type="text" id="input_fruit" name="input_fruit">
      <button type="submit">Submit</button><br><br>
      <button type="button" id="clear">Click here to Clear Local Storage</button>
   </form>
</body>
</html>

方法 2:利用動態儲存的資料。

執行此程式碼的步驟如下:

  • 步驟 1 - 在 HTML 庫中,儲存所需的 jQuery 庫。

  • 步驟 2 - 使用 localStorage.getItem() 函式查詢本地儲存中是否存在“水果”項。

  • 步驟 3 - 如果本地儲存中不存在“水果”項,則為水果名稱列表建立一個名為“水果”的新陣列。

  • 步驟 4 - 使用 localStorage.setItem() 函式將“水果”陣列作為 JSON 字串儲存在本地儲存中。

  • 步驟 5 - 使用 JSON.parse() 方法從本地儲存中解析“水果”陣列,並將其儲存在名為“水果”的變數中。

  • 步驟 6 - 使用 jQuery 的 autocomplete() 函式為輸入欄位“fruit_input”啟用自動完成功能。

  • 步驟 7 - 將 autocomplete() 函式的 source 選項設定為“水果”陣列,並設定自動聚焦。

  • 步驟 8 - 使用 jQuery click() 方法為“清除”按鈕新增單擊事件監聽器。

  • 步驟 9 - 對於單擊事件監聽器,呼叫本地儲存物件的 clear() 方法以刪除本地儲存中儲存的所有專案。

  • 步驟 10 - 儲存檔案並在 Web 瀏覽器中執行。

示例

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
   <script>
      $(document).ready(function() {

         // Check data for local storage 
         if (!localStorage.getItem("Fruits")) {
            // If not, build a Fruits array
            var Fruits = ["Persimmon", "Tangerine","Kumquat", "Clementine", "Grapefruit", "Blood orange","Dragonfruit", "Fig", "Date", "Coconut", "Avocado", "Pineapple", "Passionfruit", "Watermelon", "Honeydew", "Cantaloupe", "Jackfruit", "Lychee", "Mangosteen","Apple", "Banana", "Orange", "Mango", "Pineapple", "Kiwi", "Lemon", "Lime", "Grapefruit", "Grapes", "Strawberry", "Blueberry", "Raspberry", "Blackberry", "Cranberry", "Pomegranate", "Cherry", "Apricot", "Peach", "Plum", "Pear", "Quince", "Guava", "Papaya",  "Starfruit", "Tangelo", "Ugli fruit", "Kiwi fruit", "Mulberry", "Blackcurrant", "Redcurrant", "Goji berry", "Acai berry", "Cactus pear", "Feijoa", "Nectarine", "Soursop", "Cranberry", "Tamarind", "Yuzu", "Cherimoya"      ];

            // Hold the array in local storage as a JSON string
            localStorage.setItem("Fruits", JSON.stringify(Fruits));
         }

         // Fetch the Fruits from local storage
         var Fruits = JSON.parse(localStorage.getItem("Fruits"));

         // Utilize JQuery autocomplete function for fruit input tag
         $("#fruit_input").autocomplete({
            source: Fruits,
            autofocus: true,
         });

         // To clear local storage when clear button is clicked
         $("#clear").click(function(event) {
            localStorage.clear();
         });
      });
   </script>
</head>
<body>
   <b>Auto fill</b>
   <p></p>
   <form name="form" id="form">
      <label for="">Enter Fruit</label>
      <input type="text" id="fruit_input" name="fruit_input" />
      <button type="submit">Submit</button>
      <button id="clear">Clear Local</button>
   </form>
</body>
</html>

結論

可以使用 Web Storage API 和 jQuery 建立自動填充表單。開發者可以使用兩種方法:使用本地儲存的固定資料或動態儲存的資料。對於本地資料儲存,Web Storage API 提供了 sessionStorage 和 localStorage 方法。對於自動填充表單,建議使用 localStorage,因為它即使在關閉瀏覽器並重新開啟後也能保留資料。

更新於:2023年11月22日

瀏覽量:103

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告