Simple JavaScript CRUD : Create, Read, Update, Delete step by step by OCEC

Simple JavaScript CRUD : Create, Read, Update, Delete step by step by OCEC

Javascript CURD : 

This HTML and JavaScript code presents a basic implementation of CRUD operations for managing records. It includes a form to add new records, displaying fields for name, age, and profile picture. Users can create, update, and delete records. Existing records are shown with options to update their details or delete them. This code demonstrates how to use FileReader to handle profile picture uploads and dynamically render records using JavaScript. Styling is provided via Bootstrap CSS. It's a practical example for learning about CRUD operations within web development.

CODE :

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>JavaScript CRUD Operations</title>

  <!-- Link to Bootstrap CSS for styling -->

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <style>

    body {

      padding: 20px;

    }

    .record-card {

      margin-bottom: 10px;

    }

    .profile-img {

      width: 100px;

      height: 100px;

      object-fit: cover;

      border-radius: 50%;

    }

  </style>

</head>

<body>

  <div class="container">

    <!-- Form to add a new record -->

    <h2 class="mt-4 mb-3">JavaScript CRUD Operations</h2>

    <form id="crudForm">

      <div class="form-row">

        <div class="col-md-4 mb-3">

          <label for="name">Name</label>

          <!-- Input field for name -->

          <input type="text" class="form-control" id="name" placeholder="Enter Name">

        </div>

        <div class="col-md-4 mb-3">

          <label for="age">Age</label>

          <!-- Input field for age -->

          <input type="text" class="form-control" id="age" placeholder="Enter Age">

        </div>

        <div class="col-md-4 mb-3">

          <label for="profilePic">Profile Picture</label>

          <!-- Input field for profile picture -->

          <input type="file" class="form-control-file" id="profilePic">

        </div>

      </div>

      <!-- Button to create a new record -->

      <button type="button" class="btn btn-primary" onclick="create()">Create</button>

    </form>


 

    <!-- Display area for records -->

    <h2 class="mt-4 mb-3">Records</h2>

    <div id="recordList"></div>

  </div>


 

  <!-- JavaScript code -->

  <script>

    // Array to store records

    let records = [];


 

    // Function to create a new record

    function create() {

      const nameInput = document.getElementById("name");

      const ageInput = document.getElementById("age");

      const profilePicInput = document.getElementById("profilePic");


 

      // Get values from input fields

      const name = nameInput.value.trim();

      const age = parseInt(ageInput.value.trim());

      const profilePic = profilePicInput.files[0];


 

      // Check if all fields are filled and a profile picture is selected

      if (name && !isNaN(age) && profilePic) {

        // Read the profile picture using FileReader

        const reader = new FileReader();

        reader.onload = function (e) {

          // Store the profile picture URL

          const profilePicUrl = e.target.result;

          // Create a new record object

          const record = {

            id: Date.now().toString(),

            name: name,

            age: age,

            profilePic: profilePicUrl

          };


 

          // Add the new record to the records array

          records.push(record);

          // Render the updated list of records

          renderRecords();

          // Clear input fields

          nameInput.value = '';

          ageInput.value = '';

          profilePicInput.value = '';

        };

        reader.readAsDataURL(profilePic);

      } else {

        // Display an alert if any field is missing

        alert("Please enter valid name, age, and select a profile picture.");

      }

    }


 

    // Function to update a record

    function update(id, newName, newAge, newProfilePic) {

      const index = records.findIndex(record => record.id === id);

      if (index !== -1) {

        records[index].name = newName;

        records[index].age = newAge;

        if (newProfilePic) {

          const reader = new FileReader();

          reader.onload = function (e) {

            records[index].profilePic = e.target.result;

            renderRecords();

          };

          reader.readAsDataURL(newProfilePic);

        } else {

          renderRecords();

        }

      }

    }


 

    // Function to remove a record

    function remove(id) {

      // Confirm deletion using a popup

      const confirmation = confirm("Are you sure you want to delete this record?");

      if (confirmation) {

        // Filter out the record with the given ID

        records = records.filter(record => record.id !== id);

        // Render the updated list of records

        renderRecords();

      }

    }


 

    // Function to render the list of records

    function renderRecords() {

      const recordList = document.getElementById("recordList");

      recordList.innerHTML = '';


 

      // Loop through each record and create a card for it

      records.forEach(record => {

        const card = document.createElement("div");

        card.className = "card record-card";

        card.innerHTML = `

          <div class="card-body">

            <div class="row">

              <div class="col-md-4">

                <!-- Display profile picture -->

                <img src="${record.profilePic}" class="profile-img" alt="Profile Picture">

              </div>

              <div class="col-md-8">

                <!-- Display name and age -->

                <h5 class="card-title">${record.name}</h5>

                <p class="card-text">Age: ${record.age}</p>

                <div class="form-group">

                  <!-- Input field to update profile picture -->

                  <label for="updateProfilePic">Update Profile Picture</label>

                  <input type="file" class="form-control-file" id="updateProfilePic" onchange="update('${record.id}', '${record.name}', ${record.age}, this.files[0])">

                </div>

                <!-- Button to update record -->

                <button type="button" class="btn btn-primary mr-2" onclick="update('${record.id}', prompt('Enter new name:', '${record.name}'), parseInt(prompt('Enter new age:', ${record.age})), null)">Update</button>

                <!-- Button to delete record -->

                <button type="button" class="btn btn-danger" onclick="remove('${record.id}')">Delete</button>

              </div>

            </div>

          </div>

        `;

        recordList.appendChild(card);

      });

    }

  </script>

</body>

</html>


The JavaScript section handles CRUD operations. Functions include:

  • create(): Reads input values, validates them, and creates a new record. It uses FileReader to handle profile picture uploads.
  • update(id, newName, newAge, newProfilePic): Updates an existing record with new values. Allows for updating the profile picture.
  • remove(id): Deletes a record after confirming with the user.
  • renderRecords(): Renders the list of records dynamically, creating cards for each record with options to update or delete.

Overall, this code serves as a practical demonstration of implementing CRUD functionalities in a web application using HTML, JavaScript, and Bootstrap for styling.


Share this article







Related Posts




0 Comments



Load more Comments

Post a Comment


helllo
Ocec Copyright text of dont't copyright our content