Creating a Local Storage CRUD Application in HTML5

Creating a Local Storage CRUD Application in HTML5

Introduction

In modern web development, client-side storage solutions like Local Storage have become essential for building efficient and user-friendly applications. Local Storage allows developers to store data on the user's browser, enabling features like offline access and persistent user preferences without the need for server-side databases.

In this article, we'll walk through creating a simple CRUD (Create, Read, Update, Delete) application using HTML5, JavaScript, and Local Storage. This application will allow users to store, retrieve, update, and delete key-value pairs directly in their browser.

 

 

 

 

Table of Contents

  1. Prerequisites
  2. Project Overview
  3. Setting Up the HTML Structure
  4. Styling with CSS
  5. Implementing JavaScript Functionality
  6. Final Code
  7. Testing the Application
  8. Conclusion
  9. Additional Resources

Prerequisites

To follow along with this tutorial, you should have:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A modern web browser (e.g., Chrome, Firefox, Edge).
  • A text editor or IDE (e.g., Visual Studio Code, Sublime Text).

Project Overview

We will build a simple web page that:

  • Provides input fields for the user to enter a key and a value.
  • Offers buttons to perform Create, Read, Update, and Delete operations.
  • Displays all stored key-value pairs in a table format.
  • Utilizes Local Storage to persist data between sessions.

Setting Up the HTML Structure

Let's start by creating a basic HTML file with the necessary elements.

Create a file named local_storage_crud.html and add the following code:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Local Storage CRUD Application</title> </head> <body> <h1>Local Storage CRUD Application</h1> <input type="text" id="dataKey" placeholder="Enter Key"> <input type="text" id="dataValue" placeholder="Enter Value"> <button onclick="createData()">Create</button> <button onclick="readData()">Read</button> <button onclick="updateData()">Update</button> <button onclick="deleteData()">Delete</button> <div id="dataDisplay"></div> </body> </html>

Explanation:

  • Header (<h1>): Displays the title of the application.
  • Input Fields:
    • Key Input (#dataKey): For entering the key.
    • Value Input (#dataValue): For entering the value.
  • Buttons: Each button triggers a JavaScript function corresponding to a CRUD operation.
  • Data Display (#dataDisplay): A <div> element where we'll display the stored data.

Styling with CSS

To make the application visually appealing, we'll add some basic CSS styles.

Add the following <style> tag within the <head> section:

html
<style> body { font-family: Arial, sans-serif; margin: 20px; } input, button { margin: 5px; padding: 8px; font-size: 16px; } #dataDisplay { margin-top: 20px; } table { border-collapse: collapse; width: 100%; margin-top: 10px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f4f4f4; } button { cursor: pointer; } </style>

Explanation:

  • General Styles: Sets font family and margins for the body.
  • Inputs and Buttons: Adds margin, padding, and font size for better usability.
  • Data Display: Adds margin to separate it from the input area.
  • Table Styles: Styles the table, headers, and cells for clear data presentation.
  • Button Cursor: Changes the cursor to a pointer when hovering over buttons.

Implementing JavaScript Functionality

We'll now add JavaScript functions to handle each CRUD operation and to display the data.

Add the following <script> tag just before the closing </body> tag:

html
<script> // Function to create data function createData() { var key = document.getElementById('dataKey').value; var value = document.getElementById('dataValue').value; if (key && value) { if (localStorage.getItem(key) === null) { localStorage.setItem(key, value); alert('Data added to local storage.'); displayData(); } else { alert('Key already exists. Use Update to modify the value.'); } } else { alert('Please enter both key and value.'); } } // Function to read data function readData() { var key = document.getElementById('dataKey').value; if (key) { var value = localStorage.getItem(key); if (value !== null) { alert('Key: ' + key + '\nValue: ' + value); } else { alert('No data found for the given key.'); } } else { alert('Please enter a key to read data.'); } } // Function to update data function updateData() { var key = document.getElementById('dataKey').value; var value = document.getElementById('dataValue').value; if (key && value) { if (localStorage.getItem(key) !== null) { localStorage.setItem(key, value); alert('Data updated in local storage.'); displayData(); } else { alert('No data found for the given key. Use Create to add new data.'); } } else { alert('Please enter both key and value.'); } } // Function to delete data function deleteData() { var key = document.getElementById('dataKey').value; if (key) { if (localStorage.getItem(key) !== null) { localStorage.removeItem(key); alert('Data deleted from local storage.'); displayData(); } else { alert('No data found for the given key.'); } } else { alert('Please enter a key to delete data.'); } } // Function to display all data function displayData() { var dataDisplay = document.getElementById('dataDisplay'); dataDisplay.innerHTML = ''; if (localStorage.length > 0) { var table = '<table><tr><th>Key</th><th>Value</th></tr>'; for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); table += '<tr><td>' + key + '</td><td>' + value + '</td></tr>'; } table += '</table>'; dataDisplay.innerHTML = table; } else { dataDisplay.innerHTML = 'Local storage is empty.'; } } // Display data when the page loads window.onload = function() { displayData(); } </script>

Create Data

Function: createData()

  • Purpose: Adds a new key-value pair to Local Storage if the key doesn't already exist.
  • Logic:
    • Retrieves the key and value from input fields.
    • Checks if both key and value are provided.
    • Checks if the key already exists in Local Storage.
    • Stores the key-value pair if the key is new.
    • Calls displayData() to refresh the displayed data.

Read Data

Function: readData()

  • Purpose: Retrieves and displays the value associated with a given key.
  • Logic:
    • Retrieves the key from the input field.
    • Checks if the key is provided.
    • Fetches the value from Local Storage.
    • Displays an alert with the key and value or an error message.

Update Data

Function: updateData()

  • Purpose: Updates the value of an existing key in Local Storage.
  • Logic:
    • Retrieves the key and new value from input fields.
    • Checks if both key and value are provided.
    • Checks if the key exists in Local Storage.
    • Updates the value if the key exists.
    • Calls displayData() to refresh the displayed data.

Delete Data

Function: deleteData()

  • Purpose: Removes a key-value pair from Local Storage.
  • Logic:
    • Retrieves the key from the input field.
    • Checks if the key is provided.
    • Checks if the key exists in Local Storage.
    • Removes the key-value pair if the key exists.
    • Calls displayData() to refresh the displayed data.

Display Data

Function: displayData()

  • Purpose: Displays all key-value pairs stored in Local Storage in a table.
  • Logic:
    • Clears the existing content in the #dataDisplay element.
    • Checks if Local Storage has any data.
    • Iterates through all keys in Local Storage.
    • Builds an HTML table with all key-value pairs.
    • Inserts the table into the #dataDisplay element.

Note: The window.onload event ensures that the data is displayed as soon as the page loads.

Final Code

Combining all the sections, your final HTML file should look like this:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Local Storage CRUD Application</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } input, button { margin: 5px; padding: 8px; font-size: 16px; } #dataDisplay { margin-top: 20px; } table { border-collapse: collapse; width: 100%; margin-top: 10px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f4f4f4; } button { cursor: pointer; } </style> </head> <body> <h1>Local Storage CRUD Application</h1> <input type="text" id="dataKey" placeholder="Enter Key"> <input type="text" id="dataValue" placeholder="Enter Value"> <button onclick="createData()">Create</button> <button onclick="readData()">Read</button> <button onclick="updateData()">Update</button> <button onclick="deleteData()">Delete</button> <div id="dataDisplay"></div> <script> // Function to create data function createData() { var key = document.getElementById('dataKey').value; var value = document.getElementById('dataValue').value; if (key && value) { if (localStorage.getItem(key) === null) { localStorage.setItem(key, value); alert('Data added to local storage.'); displayData(); } else { alert('Key already exists. Use Update to modify the value.'); } } else { alert('Please enter both key and value.'); } } // Function to read data function readData() { var key = document.getElementById('dataKey').value; if (key) { var value = localStorage.getItem(key); if (value !== null) { alert('Key: ' + key + '\nValue: ' + value); } else { alert('No data found for the given key.'); } } else { alert('Please enter a key to read data.'); } } // Function to update data function updateData() { var key = document.getElementById('dataKey').value; var value = document.getElementById('dataValue').value; if (key && value) { if (localStorage.getItem(key) !== null) { localStorage.setItem(key, value); alert('Data updated in local storage.'); displayData(); } else { alert('No data found for the given key. Use Create to add new data.'); } } else { alert('Please enter both key and value.'); } } // Function to delete data function deleteData() { var key = document.getElementById('dataKey').value; if (key) { if (localStorage.getItem(key) !== null) { localStorage.removeItem(key); alert('Data deleted from local storage.'); displayData(); } else { alert('No data found for the given key.'); } } else { alert('Please enter a key to delete data.'); } } // Function to display all data function displayData() { var dataDisplay = document.getElementById('dataDisplay'); dataDisplay.innerHTML = ''; if (localStorage.length > 0) { var table = '<table><tr><th>Key</th><th>Value</th></tr>'; for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); table += '<tr><td>' + key + '</td><td>' + value + '</td></tr>'; } table += '</table>'; dataDisplay.innerHTML = table; } else { dataDisplay.innerHTML = 'Local storage is empty.'; } } // Display data when the page loads window.onload = function() { displayData(); } </script> </body> </html>

Testing the Application

  1. Open the HTML File:

    • Double-click the local_storage_crud.html file to open it in your default browser.
    • Alternatively, right-click the file and choose "Open with" followed by your preferred browser.
  2. Create Data:

    • Enter a key (e.g., username) and a value (e.g., john_doe).
    • Click the Create button.
    • An alert should confirm the addition, and the table will display the new data.
  3. Read Data:

    • Enter the key you just added (e.g., username).
    • Click the Read button.
    • An alert will display the key and its associated value.
  4. Update Data:

    • Enter the same key (e.g., username) and a new value (e.g., jane_doe).
    • Click the Update button.
    • An alert should confirm the update, and the table will reflect the new value.
  5. Delete Data:

    • Enter the key you wish to delete (e.g., username).
    • Click the Delete button.
    • An alert should confirm the deletion, and the data will be removed from the table.
  6. View All Data:

    • The table under the buttons displays all key-value pairs.
    • The table updates automatically after each operation.

Note: The data persists even if you refresh the page or close and reopen the browser, as long as Local Storage isn't cleared.

Conclusion

Congratulations! You've successfully created a simple CRUD application using HTML5 and Local Storage. This project demonstrates how you can leverage client-side storage to build interactive and stateful web applications without server-side dependencies.

Key Takeaways:

  • Local Storage:

    • Provides a way to store data locally within the user's browser.
    • Data persists between sessions unless explicitly cleared.
    • Useful for saving user preferences, offline data, and more.
  • CRUD Operations:

    • Fundamental operations for managing data.
    • Implemented using straightforward JavaScript functions.
  • User Interface:

    • Simple and intuitive UI enhances user experience.
    • Real-time updates to the data display keep users informed.

Additional Resources


Feel free to expand upon this project by adding features like data validation, search functionality, or integrating it with server-side storage for a full-stack application. Happy coding! and askink me for askpedromartins.com

Back to blog
  • ChatGPT Uncovered Podcast

    ChatGPT Uncovered Podcast

    Pedro Martins

    ChatGPT Uncovered Podcast ChatGPT Uncovered Podcast Exploring the Frontiers of AI Conversational Models Episode 1: Understanding ChatGPT Published on: May 15, 2023 Your browser does not support the audio element....

    ChatGPT Uncovered Podcast

    Pedro Martins

    ChatGPT Uncovered Podcast ChatGPT Uncovered Podcast Exploring the Frontiers of AI Conversational Models Episode 1: Understanding ChatGPT Published on: May 15, 2023 Your browser does not support the audio element....

  • Power Apps In-Depth Podcast

    Power Apps In-Depth Podcast

    Pedro Martins

    Power Apps In-Depth Podcast Power Apps In-Depth Podcast Exploring the Capabilities of Microsoft Power Apps Episode 1: Introduction to Power Apps Published on: April 20, 2023 Your browser does not...

    Power Apps In-Depth Podcast

    Pedro Martins

    Power Apps In-Depth Podcast Power Apps In-Depth Podcast Exploring the Capabilities of Microsoft Power Apps Episode 1: Introduction to Power Apps Published on: April 20, 2023 Your browser does not...

  • Exploring Power Pages Podcast

    Exploring Power Pages Podcast

    Pedro Martins

    Exploring Power Pages Podcast Exploring Power Pages Podcast Delving into the World of Microsoft Power Pages Episode 1: Getting Started with Power Pages Published on: March 10, 2023 Your browser...

    Exploring Power Pages Podcast

    Pedro Martins

    Exploring Power Pages Podcast Exploring Power Pages Podcast Delving into the World of Microsoft Power Pages Episode 1: Getting Started with Power Pages Published on: March 10, 2023 Your browser...

1 of 3