Open In App

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

Last Updated : 10 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies. The two mechanisms within Web Storage are sessionStorage and localStorage, session stores data only for a session that is until the browser is closed, local storage does the same thing but persists even when the browser is closed and reopened, thus it’s recommended to use local storage for auto-filling forms.

Now developers have two possible approaches to create autofill form.

  1. Use fixed data stored locally
  2. Use dynamically stored data

Note: Dynamically stored data is the one that gets updated from time to time, based on the user’s inputs like a form submission.

Approach 1: Data is stored locally on the browser using window.localStorage.setItem(key, value) and is then fetched in a script tag and used to auto-fill forms.

 

Example: Let us assume a case of the input field “country” and one needs to auto-fill the country field using HTML localStorage property. The following code implements to fetch and auto-complete country’s fields in the given form.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
    <script src=
    </script>
  
    <script>
  
        // Ready function runs everytime the page load
        $(document).ready(function() {
  
            // Set local storage      
            var Countries = [
                "Afghanistan", "Albania", "Algeria",
                "Armenia", "Australia", "Bahrain", 
                "Bangladesh", "Belgium", "Bhutan", 
                "Brazil", "Canada", "Chile", "China", 
                "Denmark", "Djibouti", "Egypt", 
                "Estonia", "Ethiopia", "Finland", 
                "France", "Germany", "Ghana", "Greece",
                "Greenland", "Hong Kong", "Hungary", 
                "Iceland", "India", "Indonesia", "Iran",
                "Iraq", "Ireland", "Israel", "Italy", 
                "Japan", "Jersey", "Jordan", "Kazakhstan",
                "Kuwait", "Kyrgyzstan", "Lebanon", 
                "Malaysia", "Maldives", "Mexico", "Nepal", 
                "Netherlands", "New Zealand", "North Korea",
                "Pakistan", "Palestine", "Philippines", 
                "Poland", "Qatar", "Russia", "Saudi Arabia",
                "Singapore", "South Africa", "Swaziland", 
                "Taiwan", "Thailand", "Turkey", 
                "United Kingdom", "United States of America",
                "Uruguay", "Vietnam", "Yemen", "Zimbabwe"
            ];
  
            // Fetch locally stored Countries
            var Countries = window.localStorage.getItem("Countries");
              
            // Convert it to a javascript object
            Countries = JSON.parse(Countries);
  
            // Fetch Country input tag and use JQuery 
            // autocomplete function
            $("#country_input").autocomplete({
  
                // Pass javascript object to 
                // autocomplete function
                source: Countries,
                autofocus: true,
            });
  
            // To clear local storage when clear
            // button is clicked 
            $("#clear").click(function(event) {
                localStorage.clear();
            });
        });
    </script>
</head>
  
<body>
    <h2>GeeksforGeeks</h2>
    <b>Autofilling forms </b>
  
    <form name="form" id="form">
        <label for="">Enter Country</label>
        <input type="text" id="country_input" 
                name="country_input" />
        <button type="submit">Submit</button>
        <button id="clear">Clear Local</button>
    </form>
</body>
  
</html>


Output: One demerit of this approach is that one needs to store various data locally at once which consumes memory and much of this data may never be used. In such cases dynamically storing data can help to store values frequently thus reducing memory and for cases where values can’t be predefined.

Autofilling feature

Approach 2: In this approach, developers store input form field data locally and update locally stored values for every form submission. During this process, duplicate entries are checked and only stored once. The developer can choose the number of values that should be present in the local storage.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    </script>
    </script>
  
    <script>
        // This function runs everytime the page load
        $(document).ready(function() {
  
            var Countries = [
                "Afghanistan", "Albania", "Algeria",
                "Armenia", "Australia", "Bahrain", 
                "Bangladesh", "Belgium", "Bhutan", 
                "Brazil", "Canada", "Chile", "China", 
                "Denmark", "Djibouti", "Egypt", 
                "Estonia", "Ethiopia", "Finland", 
                "France", "Germany", "Ghana", "Greece",
                "Greenland", "Hong Kong", "Hungary", 
                "Iceland", "India", "Indonesia", "Iran",
                "Iraq", "Ireland", "Israel", "Italy", 
                "Japan", "Jersey", "Jordan", "Kazakhstan",
                "Kuwait", "Kyrgyzstan", "Lebanon", 
                "Malaysia", "Maldives", "Mexico", "Nepal", 
                "Netherlands", "New Zealand", "North Korea",
                "Pakistan", "Palestine", "Philippines", 
                "Poland", "Qatar", "Russia", "Saudi Arabia",
                "Singapore", "South Africa", "Swaziland", 
                "Taiwan", "Thailand", "Turkey", 
                "United Kingdom", "United States of America",
                "Uruguay", "Vietnam", "Yemen", "Zimbabwe"
            ];
  
            // Fetch locally stored Countries
            var Countries = window.localStorage.getItem("Countries");
  
            // If countries is not available assign empty array []
            // else assign JavaScript object
            Countries = Countries === null ? [] : JSON.parse(Countries);
  
            // Fetch Country input tag and use jQuery 
            // autocomplete function
            $("#country_input").autocomplete({
  
                // Pass JavaScript object to 
                // autocomplete function
                source: Countries,
                autofocus: true,
            });
  
            // Form submission event function
            $("form").submit(function(event) {
  
                // Prevent form submission until
                // code execution
                event.preventDefault;
  
                // Fetch input field value
                var currentCountry = $("#country_input").val();
  
                // Store it on the top of the Countries
                // array at index 0
                Countries.unshift(currentCountry);
  
                // Remove the duplicate entries
                for (var i = 1; i < Countries.length; i++) {
  
                    // Countries[0] stores current input field
                    if (Countries[0] === Countries[i]) {
                        Countries.splice(i, 1);
                    }
                }
  
                // Stores only the last 10 searches
                // Developer can choose the number of 
                // entries to be stored          
                if (i === Countries.length && Countries.length > 10) {
                    Countries.pop();
                }
  
                // Stores the new list into the local 
                // storage overwriting the previous one
                window.localStorage.setItem("Countries", 
                    JSON.stringify(Countries));
  
                // Submit the form
                event.submit;
            });
  
            // To clear local storage when clear
            // button is clicked
            $("#clear").click(function(event) {
                localStorage.clear();
            });
        });
    </script>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <b>Autocomplete filling</b>
  
    <p></p>
  
    <form name="form" id="form">
        <label for="">Enter Country</label>
        <input type="text" id="country_input" 
                name="country_input" />
        <button type="submit">Submit</button>
        <button id="clear">Clear Local</button>
    </form>
</body>
  
</html>


Output:

autocomplete



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads