How to make Auto-filling Forms with jQuery and Web Storage API ?
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.
- Use fixed data stored locally
- 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.
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.
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.