Javascript tutorial with CRUD operations using HTML, CSS

 In this tutorial, we will walk through creating a simple CRUD (Create, Read, Update, Delete) application using JavaScript, HTML, and CSS without the need for a backend or database. The data will be stored in the browser's localStorage, which allows us to persist data between page refreshes.

Steps:

  1. Setting up HTML and CSS structure
  2. Building CRUD functionality with JavaScript
  3. Testing the application

1. Setting Up the Project Structure

Let's start by setting up the basic project structure.

  1. Create a folder for the project (e.g., crud-app).
  2. Inside this folder, create three files:
    • index.html
    • style.css
    • script.js

Your folder structure should look like this:

crud-app/ ├── index.html ├── style.css └── script.js

2. HTML Structure (index.html)

We will start by building the basic structure of the web page using HTML. It will include a form to create new items, a table to display the list of items, and buttons to update and delete items.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRUD App</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>CRUD App</h1> <!-- Form to Add/Edit Todo --> <form id="todo-form"> <input type="text" id="todo-input" placeholder="Enter a Todo" required> <button type="submit" id="submit-btn">Add Todo</button> </form> <h2>Todo List</h2> <table id="todo-table"> <thead> <tr> <th>Todo</th> <th>Actions</th> </tr> </thead> <tbody></tbody> </table> </div> <script src="script.js"></script> </body> </html>

Explanation:

  • Form: We have an input field where users can enter a new todo item. There is also a button to submit the form.
  • Table: This will display the list of todos. Each row will have buttons to edit or delete the todo.

3. CSS Styling (style.css)

Now, let's add some basic CSS to make our app look better.

css
/* style.css */ * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Arial, sans-serif; background-color: #f0f0f0; padding: 20px; } .container { max-width: 600px; margin: auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } h1 { text-align: center; color: #333; } form { display: flex; justify-content: space-between; margin-bottom: 20px; } input { width: 70%; padding: 10px; font-size: 16px; } button { padding: 10px 20px; font-size: 16px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } button:hover { background-color: #45a049; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } table, th, td { border: 1px solid #ddd; } th, td { padding: 12px; text-align: left; } td button { background-color: #ff9800; color: white; border: none; cursor: pointer; padding: 5px 10px; margin-right: 5px; } td button:hover { background-color: #ff5722; } tr:nth-child(even) { background-color: #f9f9f9; }

Explanation:

  • Container Styling: The main content area is centered, with padding and a background color.
  • Table Styling: The table is styled to be simple, with padding in the cells and alternating row colors.
  • Button Styling: Buttons have a simple color scheme that changes on hover.

4. JavaScript for CRUD Operations (script.js)

Now, let's write the JavaScript code to handle CRUD operations.

javascript
// script.js // Get DOM elements const todoForm = document.getElementById('todo-form'); const todoInput = document.getElementById('todo-input'); const todoTable = document.getElementById('todo-table').getElementsByTagName('tbody')[0]; // Load Todos from localStorage const loadTodos = () => { const todos = JSON.parse(localStorage.getItem('todos')) || []; todoTable.innerHTML = ''; todos.forEach((todo, index) => { const row = todoTable.insertRow(); row.innerHTML = ` <td>${todo}</td> <td> <button class="edit-btn" onclick="editTodo(${index})">Edit</button> <button class="delete-btn" onclick="deleteTodo(${index})">Delete</button> </td> `; }); }; // Save Todos to localStorage const saveTodos = (todos) => { localStorage.setItem('todos', JSON.stringify(todos)); }; // Add Todo const addTodo = (todo) => { const todos = JSON.parse(localStorage.getItem('todos')) || []; todos.push(todo); saveTodos(todos); loadTodos(); }; // Delete Todo const deleteTodo = (index) => { const todos = JSON.parse(localStorage.getItem('todos')) || []; todos.splice(index, 1); saveTodos(todos); loadTodos(); }; // Edit Todo const editTodo = (index) => { const todos = JSON.parse(localStorage.getItem('todos')) || []; todoInput.value = todos[index]; todoForm.onsubmit = (e) => { e.preventDefault(); todos[index] = todoInput.value; saveTodos(todos); loadTodos(); todoInput.value = ''; todoForm.onsubmit = addTodoForm; }; }; // Add Todo Form Submission const addTodoForm = (e) => { e.preventDefault(); if (todoInput.value.trim() !== '') { addTodo(todoInput.value); todoInput.value = ''; } }; // Event Listener for form submission todoForm.onsubmit = addTodoForm; // Initial Load of Todos loadTodos();

Explanation:

  1. Loading and Saving Todos:

    • loadTodos: This function loads todos from localStorage and displays them in the table. It is called initially and whenever the todos are updated.
    • saveTodos: This function saves the list of todos to localStorage.
  2. CRUD Operations:

    • Add Todo: The addTodo function pushes a new todo to the list and updates localStorage.
    • Delete Todo: The deleteTodo function removes a todo based on the index and updates localStorage.
    • Edit Todo: The editTodo function pre-fills the input field with the todo's value, allowing the user to edit it. After editing, the todo is updated in the list and stored in localStorage.
  3. Form Handling:

    • addTodoForm is the default form submission handler that adds a new todo when the user submits the form.

5. Testing the Application

  1. Open the index.html file in your browser.
  2. You should see:
    • A form to input new todos.
    • A table to display existing todos with "Edit" and "Delete" buttons.
  3. Test the CRUD functionality:
    • Add a new todo by typing in the input and pressing "Add Todo".
    • Edit a todo by clicking the "Edit" button.
    • Delete a todo by clicking the "Delete" button.

Conclusion

You have now created a simple CRUD app using HTML, CSS, and JavaScript with localStorage for data persistence. This is a basic example, and you can further enhance it by adding features such as:

  • Validation to ensure that todos are not empty.
  • Sorting or filtering todos based on completion status.
  • Styling improvements for better user experience.

This example is perfect for understanding the fundamentals of CRUD operations and how to interact with localStorage in the browser.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics