Back to feed

Storing Form Data in Local Storage with jQuery

Learn how to store form data in Local Storage using jQuery to enhance user experience and prevent data loss.

Storing Form Data in Local Storage with jQuery

We've all experienced it: meticulously filling out a form only to encounter an error that wipes all our entries. The larger and more complex the form, the more frustrating this becomes. While some browsers may save your inputs, this isn't always guaranteed. After a couple of mishaps, motivation can dwindle.

To ensure that users of your projects do not face such frustrating experiences, this article presents a straightforward solution. While data can be directly transferred to a database, this isn't always necessary or practical for every project. Therefore, this guide focuses on utilizing "Local Storage."

As the name suggests, Local Storage allows data to be stored locally in the user's browser. This not only enables recovery of data in case of an error but also allows users to take a break and return later to continue where they left off.

In this guide, we will be using Mozilla's Firefox browser. However, the data storage functionality is compatible with any modern browser.

In Firefox, users can easily view what is stored in Local Storage by navigating to "More Tools" -> "Web Developer Tools." Under the "Storage" tab, one can find the "Local Storage" option.

01. Saving Data

The function activates with each input, storing data in a JSON format that includes the ID and the entered value. The ID is crucial for later associating the value with the correct input field. Using ":input," all input fields are considered, and a precise definition of which fields to save is also possible. Utilizing ".each," we iterate through all fields and store the data in our JSON using ".push."

$(':input').on('input', function() {
	var formname = "demo-form";
	var formData = [];
	localStorage.removeItem(formname);
	$('form input, form select').not('input[type="hidden"]').each(function(){
		formData.push({ id: this.id, value: this.value});
	});
	localStorage.setItem(formname, JSON.stringify(formData));
});

02. Restoring Data

If a user accidentally closes the tab and returns later, they will find all their data intact. This is achieved by first checking if there is any data in Local Storage. If the answer is "true," we load all data from the JSON using a "for" loop.

$(document).ready(function() {
	var formname = "demo-form";
	if(localStorage.getItem(formname) != undefined){
		formData = JSON.parse(localStorage.getItem(formname));
		for (var i = 0; i < formData.length; i++) {
			$('[id='+formData[i].id+']').val(formData[i].value);
		}
	}
});

03. Demo Project

To illustrate this concept better, I've created a small demo project using Bootstrap. To make it easy to see what is stored in Local Storage, I've included a code tag that displays the JSON. However, it's recommended to use the browser's built-in functionality to view the data.

LocalStorage

		About
		Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

		LocalStorage

			LocalStorage
			Store data in LocalStorage

			LocalStorage Reader

var formname = "demo-form";
// Read localStorage
$(document).ready(function() {
	if(localStorage.getItem(formname) != undefined){
		formData = JSON.parse(localStorage.getItem(formname));
		for (var i = 0; i < formData.length; i++) {
			$('[id='+formData[i].id+']').val(formData[i].value);
		}
		// Only for demo
		$('.output').html(localStorage.getItem(formname));
	}
});
// Save in localStorage
$(':input').on('input', function() {
	var formData = [];
	localStorage.removeItem(formname);
	$('form input, form select').not('input[type="hidden"]').each(function(){
		formData.push({ id: this.id, value: this.value});
	});
	localStorage.setItem(formname, JSON.stringify(formData));
	// Only for demo
	$('.output').html(localStorage.getItem(formname));
});
// Clean localStorage
$("#clean-form").on('click', function() {
	$("#demo-form")[0].reset();
	localStorage.removeItem(formname);
	location.reload(true);
});

04. Download

I've compiled all the files for this guide to facilitate a quicker setup. I hope you enjoy working on the project as much as I did, and I wish you success in your endeavors.

artsblog-localstorage-master

Filesize: 1.4 MB