Manage Data in Window.LocalStorage Tutorial

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

  1. localStorage.setItem('system_name', 'Simple Web Application');
  2. localStorage.setItem('categories', '["News", "Popular", "Featured"]'');

Rereiving Data

  1. const system_name = localStorage.getItem('system_name');
  2. const categories = localStorage.getItem('categories');

Removing Items

  1. localStorage.removeItem('system_name');
  2. localStorage.removeItem('categories');

Removing All Items

  1. localStorage.clear();

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.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>JS Local Storage</title>
  8. <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"
  9. />
  10. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  11. <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>
  12. <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>
  13. <script src="./script.js"></script>
  14. </head>
  15. html,
  16. body {
  17. height: 100%;
  18. width: 100%;
  19. }
  20.  
  21. <body class="bg-gradient bg-primary bg-opacity-25">
  22. <div class="content py-5 px-2">
  23. <div class="container">
  24. <div class="card rounded-0">
  25. <div class="card-body">
  26. <div class="container-fluid">
  27. <h3 class="text-center">Using JS Local Storage</h3>
  28. <hr>
  29. <div class="row">
  30. <div class="col-lg-5">
  31. <div class="card shadow rounded-0">
  32. <div class="card-header">
  33. <div class="card-title">Member Form</div>
  34. </div>
  35. <div class="card-body">
  36. <div class="container-fluid">
  37. <form action="" id="member-form">
  38. <input type="hidden" name="id" id="id">
  39. <div class="mb-3">
  40. <label for="name" class="control-label">Fullname</label>
  41. <input type="text" class="form-control form-control-sm rounded-0" id="name" name="name" required="required">
  42. </div>
  43. <div class="mb-3">
  44. <label for="contact" class="control-label">Contact</label>
  45. <input type="text" class="form-control form-control-sm rounded-0" id="contact" name="contact" required="required">
  46. </div>
  47. <div class="mb-3">
  48. <label for="email" class="control-label">Email</label>
  49. <input type="email" class="form-control form-control-sm rounded-0" id="email" name="email" required="required">
  50. </div>
  51. <div class="mb-3">
  52. <label for="address" class="control-label">Address</label>
  53. <textarea rows="3" class="form-control form-control-sm rounded-0" id="address" name="address" required="required"></textarea>
  54. </div>
  55. </form>
  56. </div>
  57. </div>
  58. <div class="card-footer py-2 text-center">
  59. <button class="btn btn-sm btn-primary bg-gradient rounded-0" form="member-form"><i class="fa fa-save"></i> Save</button>
  60. <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>
  61. </div>
  62. </div>
  63. </div>
  64. <div class="col-lg-7">
  65. <table class="table table-striped table-bordered" id="member-tbl">
  66. <tr class="bg-gradient bg-primary text-light">
  67. <th class="p-1 text-center">#</th>
  68. <th class="p-1 text-center">Name</th>
  69. <th class="p-1 text-center">Contact</th>
  70. <th class="p-1 text-center">Email</th>
  71. <th class="p-1 text-center">Address</th>
  72. <th class="p-1 text-center">Action</th>
  73. </tr>
  74. </thead>
  75. </table>
  76. </div>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. </div>
  83. </body>
  84. <noscript id="btn-action">
  85. <div class="text-center">
  86. <div class="btn-group btn-group-sm">
  87. <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>
  88. <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>
  89. </div>
  90. </div>
  91. </html>

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.

  1. // Retrieve Data stored in local storage
  2. var members = !!localStorage.getItem('members') ? $.parseJSON(localStorage.getItem('members')) : {};
  3.  
  4. // Fetch and Display Data From Local Storage
  5. function load_data() {
  6. var tbl = $('#member-tbl')
  7. if (Object.keys(members).length > 0) {
  8. var i = 1;
  9. tbl.find('tbody').html('')
  10. Object.keys(members).map(k => {
  11. var data = members[k]
  12. var id = k
  13. var tr = $('<tr>')
  14. var btns = $($('noscript#btn-action').html()).clone()
  15. tr.append('<th class="text-center p-1 align-middle">' + (i++) + '</th>')
  16. tr.append('<td class="p-1 align-middle">' + (data.name) + '</td>')
  17. tr.append('<td class="p-1 align-middle">' + (data.contact) + '</td>')
  18. tr.append('<td class="p-1 align-middle">' + (data.email) + '</td>')
  19. tr.append('<td class="p-1 align-middle">' + (data.address) + '</td>')
  20. tr.append('<td class="p-1 align-middle text-center">' + (btns[0].outerHTML) + '</td>')
  21. tbl.find('tbody').append(tr)
  22.  
  23. // Edit Data
  24. tr.find('.edit-data').click(function() {
  25. $('#id').val(k)
  26. $('#name').val(data.name)
  27. $('#contact').val(data.contact)
  28. $('#email').val(data.email)
  29. $('#address').val(data.address)
  30. })
  31.  
  32. // Delete Data
  33. tr.find('.delete-data').click(function() {
  34. if (confirm('Are your sure to delete ' + data.name + ' from list?') == true) {
  35.  
  36. // Delete Data and Update Local Storage
  37. if (!!members[k])
  38. delete members[k];
  39. localStorage.setItem('members', JSON.stringify(members));
  40. alert("Member Details has been deleted successfully.");
  41. location.reload();
  42.  
  43. }
  44. })
  45.  
  46. })
  47. } else {
  48. var tr = $('<tr>')
  49. tr.append('<th colspan="6" class="text-center fw-bold p-1">No records found.</th>')
  50. tbl.find('tbody').html(tr[0].outerHTML)
  51. }
  52. }
  53.  
  54.  
  55. $(function() {
  56. load_data()
  57.  
  58. // Insert INTO Local Storage
  59. $('#member-form').submit(function(e) {
  60. e.preventDefault();
  61. var id = $('#id').val()
  62. var name = $('#name').val()
  63. var contact = $('#contact').val()
  64. var email = $('#email').val()
  65. var address = $('#address').val()
  66. var _this = $(this)
  67. if (_this[0].checkValidity() == false) {
  68. _this[0].reportValidity()
  69. return false;
  70. }
  71. var item = { "name": name, "contact": contact, "email": email, "address": address }
  72. if (id == '') {
  73. members[(Object.keys(members).length > 0 ? Object.keys(members).length : 0)] = item
  74. } else {
  75. members[id] = item
  76. }
  77. localStorage.setItem('members', JSON.stringify(members));
  78. if (id == '')
  79. alert("Member Details has been saved successfully.");
  80. else
  81. alert("Member Details has been updated successfully.");
  82. location.reload();
  83. })
  84.  
  85. // Reset Hidden Inputs
  86. $('#member-form').on('reset', function() {
  87. $('input[type="hidden"]').val('')
  88. })
  89.  
  90. })

The following image is the result or out of the simple applcation using the provided scripts above.

window.localStorage()

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 :))

Comments

Submitted byoleteacheron Fri, 06/10/2022 - 04:30

Maybe make related tutorial on how to retrieve the data and ZIP for export...

 

Thanks for taking time to share.

Add new comment