How to make Auto-filling Forms with jQuery and Web Storage API?


By automatically filling in common fields like name, email, and address, autofill forms have grown in popularity as a feature on websites and mobile applications. When developing autofill forms, developers have two options: either utilize locally stored fixed data or use dynamic data that is periodically updated based on user inputs.

The Web Storage API is one of the most important resources available to developers for local data storage. It offers techniques for browsers to store key/value pairs in a more natural way than with cookies. SessionStorage and localStorage are the two Web Storage techniques; while sessionStorage only keeps data for the duration of a session, or until the browser is closed, localStorage survives even when the browser is closed and reopened. Consequently, it is recommended to use localStorage for auto-filling forms.

We will examine two distinct methods for building autofill forms using the Web Storage API in this article. The first method involves using window.localStorage.setItem(key, value) to local store fixed data that is later retrieved in a script tag and used to automatically fill out forms. The second strategy entails saving input.

Approaches

To make Auto fill forms with JQuery as well as with Web Storage API we can follow the two methods −

  • Utilizing local fixed data.

  • Utilizing dynamically stored data.

Let us look into both approaches −

Approach 1: Utilizing local fixed data

This approach performs some straightforward frontend user interactions, transmits some data to the server, and gives the user the option to erase any previously stored data.

Algorithm

The steps to run this code are as follows −

  • Step 1 − Build a fruit name in an array.

  • Step 2 − The autocomplete widget is created with data source as fruit array and fruit input field.

  • Step 3 − As the user enters the fruit name in the input field the automatically filled widget tried to pick the correct choice for autofill.

  • Step 4 − The fruit name is submitted and sent to the server.

Example

<!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>

Approach-2: Utilizing dynamically stored data.

The steps to run this code are as follows −

  • Step 1 − In the HTML library, hold the required jQuery libraries.

  • Step 2 − Look for whether the 'Fruits' item is there in the local storage utilizing the localStorage.getItem() function.

  • Step 3 − If the 'Fruits' item is not available in local storage, build a new array termed 'Fruits' for the fruit names list.

  • Step 4 − Hold the 'Fruits' array in local storage as a JSON string utilizing the localStorage.setItem() function.

  • Step 5 − Parse the 'Fruits' array from local storage utilizing JSON.parse() method and hold it in a variable termed 'Fruits'.

  • Step 6 − Utilize jQuery's autocomplete() function to enable autocomplete functionality to the input field 'fruit_input'.

  • Step 7 − Put the source option of autocomplete() function to the 'Fruits' array, and set autofocus.

  • Step 8 − Utilize the click event listener to the 'clear' button utilizing jQuery click() method.

  • Step 9 − For the click event listener, the clear() method is called from the local storage object to delete all stored items that are in the local storage.

  • Step 10 − Save the file as well as execute it in a web browser.

Example

<!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>

Conclusion

With the utilization of the Web Storage API as well as jQuery, autofill forms might well be created. Utilizing locally stored fixed data or dynamically saved data are the two methods available to developers. For local data storage, the Web Storage API offers the sessionStorage and localStorage methods. For autofill forms, localStorage is advised because it persists even after the browser is closed and reopened.

Updated on: 22-Nov-2023

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements