HTML Form is the most common way to collect user inputs on a website. When there are many fields to fill or there is a field with a long value to input, caching the inputted value is not a bad idea. We cache inputs so users can continue to fill the fields if they accidentally close the page or browser, or move to another page. This article will show you how to cache input with localStorage.
Note: Don’t store any sensitive information, e.g., credit card or users passwords in localStorage!!
What is localStorage
LocalStorage is an object of javascript that enables us to store strings to local storage space. The maximum data that can be stored is 5MB. LocalStorage is specific to the origin of the page. It means the storage of a domain is not accessible by another domain. LocalStorage is supported by all major browsers.
These are the function of localStorage that can be used to access the data:
setItem(key, value)
getItem(key)
removeItem(key)
clear()
Use localStorage to cache form inputs
We will create a simple HTML page with a form and some inputs. For each input, we will add oninput
listener that handles the caching. The cache is retrieved when the page is loaded. Then we will see how it behave after we implement caching.
We will use this simple HTML in this example:
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
</head>
<body>
<h2>This page 1</h2>
<form action="/page2.html" id="myForm" >
<input name="fullName" type="text" oninput="cacheInput(this)"><br>
<input name="address" type="text" oninput="cacheInput(this)"><br>
<input name="favoriteFood" type="text" oninput="cacheInput(this)"><br>
<input type="submit" value="submit">
</form>
<br>
<a href="/page2.html">Go to page 2</a>
</body>
</html>
page1.html
. This is a simple HTML with a form and some inputs. There is a link to another page to test if the cache is working or not. Just create another HTML file with a link back to page1.On every input we listen oninput
event and handle it with cacheInput
function.
function cacheInput(e) {
localStorage.setItem(e.attributes["name"].value, e.value)
}
setItem
function of localStorage with input’s name as key.On document load, we need to check if our inputs have saved data in the storage. If there is a cache, load the cache and set it to our form inputs.
window.onload = function () {
let form = document.getElementById("myForm");
let inputs = form.children;
for (let i = 0; i < inputs.length; i++) {
let el = inputs[i];
if (el.tagName.toLowerCase() != "input" || el.attributes["type"].value != "text") {
continue
}
let cachedVal = localStorage.getItem(el.attributes["name"].value)
if (cachedVal != null) {
el.value = cachedVal;
}
}
}
Now let’s open the file in the browser. For this example, I use golang as static files server. You can use another server if you like.
A static file server with golang:
package main
import (
"log"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("assets"))
http.Handle("/", http.StripPrefix("/", fs))
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
It will serve all files in the assets
directory and listen to requests on port 3000.
Run command go run main.go
then open http://localhost:3000/page1.html in your browser. You will see your page.
Try to input something in the fields. Don’t submit yet. Click go to page2, then click back to page1. You will see your previously inputted text in the field. You may also want to try to close and reopen the page. Then try to submit the form and go back to page1. You will see that the cache persists even after we submit the form. To clear the cache on submit, you can add onsubmit
listener to the form.
<form action="/submitted.html" id="myForm" onsubmit="clearCache()">
function clearCache() {
localStorage.clear()
}
LocalStorage is very useful and has some advantages compared to cookies. Other than having bigger capacity than cookies, localStorage is not sent in every request to the backend, so that can save bandwidth for data that may be unused.
The most important thing to remember: Don’t store any sensitive information, e.g., credit card or users passwords in localStorage!!