In this tutorial, we will tackle about Managing Data using window.localStorage() in JavaScript. Here, I will be providing a simple application source code that contains a CRUD (Create, Read, Update, and Delete) operations.
What is localStorage in JavaSctipt?
The localStorage is a property of the window that allows you to store data. It has no expiration. Save key-value data in your web browser.
When should I use localStorage?
You can use localStorage to store data that is not sensitive or available to the public. This can be useful for some web application projects to temporarily store the data such as the shopping cart feature for an eCommerce Project. Do not use this to store sensitive information because data stored in localStorage is easy to at the client-side.
Example Usage
Storing Data
localStorage.setItem('system_name', 'Simple Web Application');
localStorage.setItem('categories', '["News", "Popular", "Featured"]'');
Rereiving Data
const system_name = localStorage.getItem('system_name');
const categories = localStorage.getItem('categories');
Removing Items
localStorage.removeItem('system_name');
localStorage.removeItem('categories');
Removing All Items
The Following source scripts is a simple web application that stores and manage the member data using localStorage.
Interface
The following script is an HTML file naming index.html. The scripts contains the scripts of the element that are displayed or shown at the web page.
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
html,
body {
height: 100%;
width: 100%;
}
<body class="bg-gradient bg-primary bg-opacity-25">
<div class="content py-5 px-2">
<div class="card rounded-0">
<div class="container-fluid">
<h3 class="text-center">Using JS Local Storage
</h3>
<div class="card shadow rounded-0">
<div class="card-header">
<div class="card-title">Member Form
</div>
<div class="container-fluid">
<form action="" id="member-form">
<input type="hidden" name="id" id="id">
<label for="name" class="control-label">Fullname
</label>
<input type="text" class="form-control form-control-sm rounded-0" id="name" name="name" required="required">
<label for="contact" class="control-label">Contact
</label>
<input type="text" class="form-control form-control-sm rounded-0" id="contact" name="contact" required="required">
<label for="email" class="control-label">Email
</label>
<input type="email" class="form-control form-control-sm rounded-0" id="email" name="email" required="required">
<label for="address" class="control-label">Address
</label>
<textarea rows="3" class="form-control form-control-sm rounded-0" id="address" name="address" required="required"></textarea>
<div class="card-footer py-2 text-center">
<button class="btn btn-sm btn-primary bg-gradient rounded-0" form="member-form"><i class="fa fa-save"></i> Save
</button>
<button type="reset" class="btn btn-sm btn-light bg-light bg-gradient border rounded-0" form="member-form"><i class="fa fa-times"></i> Cancel
</button>
<table class="table table-striped table-bordered" id="member-tbl">
<tr class="bg-gradient bg-primary text-light">
<th class="p-1 text-center">#
</th>
<th class="p-1 text-center">Name
</th>
<th class="p-1 text-center">Contact
</th>
<th class="p-1 text-center">Email
</th>
<th class="p-1 text-center">Address
</th>
<th class="p-1 text-center">Action
</th>
<div class="text-center">
<div class="btn-group btn-group-sm">
<button class="btn btn-sm btn-primary bg-gradient rounded-0 edit-data text-xs" title="Edit Data" type="button"><small><i class="fa fa-edit text-xs"></i></small></button>
<button class="btn btn-sm btn-danger bg-gradient rounded-0 delete-data text-xs" title="Delete Data" type="button"><small><i class="fa fa-trash text-xs"></i></small></button>
Main Script
The following script is the JavaScript file naming script.js. This contains the script of the application that allows the users to store, retrieve, and delete data in localStorage.
// Retrieve Data stored in local storage
var members = !!localStorage.getItem('members') ? $.parseJSON(localStorage.getItem('members')) : {};
// Fetch and Display Data From Local Storage
function load_data() {
var tbl = $('#member-tbl')
if (Object.keys(members).length > 0) {
var i = 1;
tbl.find('tbody').html('')
Object.keys(members).map(k => {
var data = members[k]
var id = k
var tr = $('<tr>')
var btns = $($('noscript#btn-action').html()).clone()
tr.append('<th class="text-center p-1 align-middle">' + (i++) + '</th>')
tr.append('<td class="p-1 align-middle">' + (data.name) + '</td>')
tr.append('<td class="p-1 align-middle">' + (data.contact) + '</td>')
tr.append('<td class="p-1 align-middle">' + (data.email) + '</td>')
tr.append('<td class="p-1 align-middle">' + (data.address) + '</td>')
tr.append('<td class="p-1 align-middle text-center">' + (btns[0].outerHTML) + '</td>')
tbl.find('tbody').append(tr)
// Edit Data
tr.find('.edit-data').click(function() {
$('#id').val(k)
$('#name').val(data.name)
$('#contact').val(data.contact)
$('#email').val(data.email)
$('#address').val(data.address)
})
// Delete Data
tr.find('.delete-data').click(function() {
if (confirm('Are your sure to delete ' + data.name + ' from list?') == true) {
// Delete Data and Update Local Storage
if (!!members[k])
delete members[k];
localStorage.setItem('members', JSON.stringify(members));
alert("Member Details has been deleted successfully.");
location.reload();
}
})
})
} else {
var tr = $('<tr>')
tr.append('<th colspan="6" class="text-center fw-bold p-1">No records found.</th>')
tbl.find('tbody').html(tr[0].outerHTML)
}
}
$(function() {
load_data()
// Insert INTO Local Storage
$('#member-form').submit(function(e) {
e.preventDefault();
var id = $('#id').val()
var name = $('#name').val()
var contact = $('#contact').val()
var email = $('#email').val()
var address = $('#address').val()
var _this = $(this)
if (_this[0].checkValidity() == false) {
_this[0].reportValidity()
return false;
}
var item = { "name": name, "contact": contact, "email": email, "address": address }
if (id == '') {
members[(Object.keys(members).length > 0 ? Object.keys(members).length : 0)] = item
} else {
members[id] = item
}
localStorage.setItem('members', JSON.stringify(members));
if (id == '')
alert("Member Details has been saved successfully.");
else
alert("Member Details has been updated successfully.");
location.reload();
})
// Reset Hidden Inputs
$('#member-form').on('reset', function() {
$('input[type="hidden"]').val('')
})
})
The following image is the result or out of the simple applcation using the provided scripts above.
I have uploaded the working source code zip file on this website. You can download and test it on your end. The download button is located below this article.
I hope this Tutorial will help you with what you are looking for and for your future web application projects. Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :))