Perform CRUD Operations with Vanilla JavaScript | Source Code Included

Faraz

By Faraz -

Learn how to create a web application that allows you to perform CRUD operations using Vanilla JavaScript. This tutorial will cover everything you need to know, with source code included.


vanilla javascript crud operation with source code learn to create, read, update, and delete data.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations that can be performed on data. These operations are fundamental in web development, as they allow us to perform actions on data that is stored in a database or other data source.

In this tutorial, we will be using vanilla JavaScript to perform CRUD operations and create a web application that can create, read, update, and delete data. Vanilla JavaScript refers to using pure JavaScript without any external libraries or frameworks. This tutorial is perfect for beginners who want to learn how to build a web application from scratch or developers who want to improve their JavaScript skills.

Throughout this tutorial, we will cover all aspects of CRUD operations, from setting up the project to creating, reading, updating, and deleting data. We will provide step-by-step instructions and include code snippets and screenshots to make the process as clear as possible. By the end of this tutorial, you will have a fully functional web application that can perform CRUD operations.

Let's perform CRUD operations using Vanilla JavaScript step by step.

Join My Telegram Channel to Download the Projects Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our CRUD application.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

The below code is an HTML document that contains a web page that allows users to perform CRUD (Create, Read, Update, Delete) operations on a list of data.

The code defines the structure and content of the web page using various HTML elements such as headings, input fields, buttons, tables, and div containers. It also includes a link to an external CSS file named "styles.css" that defines the visual style of the web page.

The web page has a header with the title "CRUD Operations" and a container that holds the input fields for adding new data, a table that displays the existing data, and a container for updating data. The table has three columns for the name, email, and actions of each item in the data list.

Users can add new data by entering a name and email address in the input fields and clicking the "Add" button. The data is then displayed in a new row in the table. Users can also update or delete existing data by clicking the corresponding buttons in the "Actions" column of the table.

The "update-container" div is initially hidden, but it appears when the user clicks the "Edit" button in the "Actions" column. The user can then modify the data in the input fields and click the "Update" button to save the changes or the "Cancel" button to discard them.

The web page uses a JavaScript file named "script.js" to implement the functionality of the add, update, and delete operations. The JavaScript code interacts with the HTML elements to get and manipulate data and update the display of the web page.

This is the basic structure of our CRUD application using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the CRUD application is in place, the next step is to add styling to the CRUD application using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our CRUD application.

Here is a breakdown of what each section of the code does:

#container defines a container element with a maximum width of 800 pixels and centers it horizontally using auto margins. The text inside the container is centered as well.

h1 removes the top margin from any heading 1 element.

#input-container applies a bottom margin of 20 pixels to a specific container element.

#name-input, #email-input, #update-name-input, and #update-email-input apply styles to input fields with specific IDs. They have a padding of 10 pixels, a font size of 16 pixels, a margin-right of 10 pixels, a border radius of 5 pixels, and a 1-pixel solid border in a light gray color. These styles are also applied when the input fields are in focus.

button defines styles for buttons, including padding, font size, cursor type, background color, font color, and border radius. The buttons have no border and are of one color (#4CAF50).

button:hover defines a new background color when a user hovers over the button.

table applies styles to a table element, including a 100% width and a bottom margin of 20 pixels. It also collapses the borders between cells.

th and td define styles for table headers and cells, including padding and text alignment. The cells have a 1-pixel solid border at the bottom.

th applies a background color of #4CAF50 and white text color to the table headers.

#update-container hides a specific container element using the display:none property. It also applies a top margin of 20 pixels.

#update-btn and #cancel-btn apply styles to specific buttons with IDs. They have different background colors.

.edit-btn and .delete-btn apply styles to buttons with specific classes. They have different background colors, and the delete button also has a left margin of 10 pixels.

This will give our CRUD application an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

#container {
  max-width: 800px;
  margin: 0 auto;
  text-align: center;
}

h1 {
  margin-top: 0;
}

#input-container {
  margin-bottom: 20px;
}

#name-input,
#email-input,
#update-name-input,
#update-email-input {
  padding: 10px;
  font-size: 16px;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

#name-input:focus,
#email-input:focus,
#update-name-input:focus,
#update-email-input:focus {
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
  box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
}

button:hover {
  background-color: #3e8e41;
}

table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 20px;
}

th,
td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #4CAF50;
  color: white;
}

#update-container {
  display: none;
  margin-top: 20px;
}

#update-btn {
  background-color: #2196F3;
}

#cancel-btn {
  background-color: #f44336;
}

.edit-btn{
  background-color: #ffc107;
}

.delete-btn{
  background-color: #dc3545;
  margin-left:10px;
} 

Step 3 (JavaScript Code):

Finally, we need to create a CRUD function in JavaScript.

The variables defined at the beginning of the code are used to reference various elements of the HTML document using their respective ID attributes. These elements include input fields for the user's name and email address, a button to add new users to the list, a table body element where the list of users is displayed, input fields and buttons for updating user information, and a regular expression that is used to validate email addresses.

The functions defined in the code include:

renderTable(): This function iterates over the list of users and creates table rows that display their name, email address, and buttons to edit or delete the user. This function is called initially to display any existing users stored in local storage and is also called after adding, updating, or deleting users to update the display.

addUser(): This function gets the user's name and email address from the input fields, validates the email address using the regular expression, creates a new user object with a unique ID and the input values, adds the new user to the list of users, stores the updated list in local storage, clears the input fields, and calls renderTable() to update the display.

updateUser(): This function gets the updated name and email address from the input fields, validates the email address using the regular expression, finds the index of the user to be updated in the list of users, updates the user's name and email address in the list, stores the updated list in local storage, hides the update form, and calls renderTable() to update the display.

showUpdateForm(userId): This function is called when the user clicks the edit button for a specific user. It finds the user in the list of users using their ID, displays the update form with the user's current information pre-populated, and adds event listeners to the update and cancel buttons.

hideUpdateForm(): This function is called when the user clicks the cancel button in the update form. It clears the input fields, removes event listeners from the update and cancel buttons, hides the update form, and sets the currentUserId variable to null.

deleteUser(userId): This function is called when the user clicks the delete button for a specific user. It removes the user from the list of users, stores the updated list in local storage, hides the update form if there are no more users left, and calls renderTable() to update the display.

Finally, an event listener is added to the add button to call the addUser() function when clicked, and the renderTable() function is called initially to display any existing users stored in local storage.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

// Variables
const nameInput = document.getElementById("name-input");
const emailInput = document.getElementById("email-input");
const addBtn = document.getElementById("add-btn");
const tableBody = document.getElementById("table-body");
const updateNameInput = document.getElementById("update-name-input");
const updateEmailInput = document.getElementById("update-email-input");
const updateBtn = document.getElementById("update-btn");
const cancelBtn = document.getElementById("cancel-btn");
let users = JSON.parse(localStorage.getItem("users")) || [];
let currentUserId = null;
const validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

// Functions
function renderTable() {
  tableBody.innerHTML = "";
  for (let i = 0; i < users.length; i++) {
    const user = users[i];
    const tr = document.createElement("tr");
    const idTd = document.createElement("td");
    const nameTd = document.createElement("td");
    const emailTd = document.createElement("td");
    const actionsTd = document.createElement("td");
    const editBtn = document.createElement("button");
    editBtn.className = "edit-btn";
    const deleteBtn = document.createElement("button");
    deleteBtn.className = "delete-btn";
    idTd.innerText = user.id;
    nameTd.innerText = user.name;
    emailTd.innerText = user.email;
    editBtn.innerText = "Edit";
    deleteBtn.innerText = "Delete";
    editBtn.addEventListener("click", () => {
      showUpdateForm(user.id);
    });
    deleteBtn.addEventListener("click", () => {
      deleteUser(user.id);
    });
    actionsTd.appendChild(editBtn);
    actionsTd.appendChild(deleteBtn);
    tr.appendChild(idTd);
    tr.appendChild(nameTd);
    tr.appendChild(emailTd);
    tr.appendChild(actionsTd);
    tableBody.appendChild(tr);
  }
}

function addUser() {
  const name = nameInput.value.trim();
  const email = emailInput.value.trim();
  if(email.match(validRegex)){
    if(name && email != null){
      var id = 1;
      var val = users.map(function(x){return x.id; }).indexOf(id);
      while(val != -1){
	    id++;
	    val = users.map(function(x){return x.id; }).indexOf(id);
  }
      const user = {
        id: id,
        name: name,
        email: email,
      };
      users.push(user);
      localStorage.setItem("users", JSON.stringify(users));
      nameInput.value = "";
      emailInput.value = "";
      renderTable();
    }else{
      alert("Name is Required");
    }
  }else{
    alert("Invalid email address!");
  }
}

function updateUser() {
  const name = updateNameInput.value;
  const email = updateEmailInput.value;
  if(email.match(validRegex)){
    const index = users.findIndex((user) => user.id === currentUserId);
    if (index !== -1) {
      users[index].name = name;
      users[index].email = email;
      localStorage.setItem("users", JSON.stringify(users));
      hideUpdateForm();
      renderTable();
    }
  }else{
    alert("Invalid email address!");
  }
}

function showUpdateForm(userId) {
  const user = users.find((user) => user.id === userId);
  if (user) {
    updateNameInput.value = user.name;
    updateEmailInput.value = user.email;
    currentUserId = user.id;
    updateBtn.addEventListener("click", updateUser);
    cancelBtn.addEventListener("click", hideUpdateForm);
    updateBtn.style.display = "inline-block";
    cancelBtn.style.display = "inline-block";
    updateNameInput.style.display = "inline-block";
    updateEmailInput.style.display = "inline-block";
    document.getElementById("update-container").style.display = "block";
  }
}

function hideUpdateForm() {
  updateNameInput.value = "";
  updateEmailInput.value = "";
  currentUserId = null;
  updateBtn.removeEventListener("click", updateUser);
  cancelBtn.removeEventListener("click", hideUpdateForm);
  updateBtn.style.display = "none";
  cancelBtn.style.display = "none";
  updateNameInput.style.display = "none";
  updateEmailInput.style.display = "none";
  document.getElementById("update-container").style.display = "none";
}

function deleteUser(userId) {
  users = users.filter((user) => user.id !== userId);
  localStorage.setItem("users", JSON.stringify(users));
  if (users.length == 0){
    hideUpdateForm();
  };
  renderTable();
}

// Event Listeners
addBtn.addEventListener("click", addUser);

// Initialize table
renderTable();

Final Output:

vanilla javascript crud operation with source code learn to create, read, update, and delete data.gif

Conclusion:

In this tutorial, we learned how to use vanilla JavaScript to perform CRUD operations and build a web application that can create, read, update, and delete data. We started by setting up the project, including installing the required dependencies, creating a basic HTML and CSS file structure, and linking our JavaScript files.

Next, we created the data structure and a form to add new data. We also learned how to display the data on the page and retrieve all data and a specific data item. We then moved on to updating the data, including creating a form to edit data, updating data in the data structure, and updating data on the page. Finally, we covered how to delete data, including creating a button to delete data, removing data from the data structure, and removing data from the page.

We hope that this tutorial has provided a comprehensive introduction to performing CRUD operations with vanilla JavaScript. By understanding how to perform these basic operations, you can build more complex web applications that store and manipulate data.

To continue learning, we recommend exploring different JavaScript frameworks and libraries, such as React and Vue.js. These can help you build more advanced web applications and streamline the development process.

Thank you for following along with this tutorial. We hope you found it helpful and informative.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post