CRUD WITH VANILLA JAVASCRIPT
Being a developer you must have come to a point of wanting to Create, Read, Update, and Delete data when building a web or mobile application.
Things like arrays and objects are there to hold the user dynamic data. Being able to store and Update this data is very important to take proper control over what happens with the data.
On this, you are going to see and learn how to perform a CRUD operation on the form input data with a Product_List_App we are going to be building using vanilla JavaScript.
Let us create our product_List_App files. You may use any of your preferred HTML editors, but I am using visual studio code(vscode) on this course.
On your editor open a new folder, name it Product_List_App, inside it create a file, name it product.html. Go inside the HTML file we created above to add this;
Above we have created an HTML file, opened a form, and add our inputs for user values, I also added a placeholder and name attribute to the input elements for proper clarification. In the input elements, an id attribute was added also which will give us the power to get the values of the input elements dynamically.
We also added the table element that will hold all of our products, a table head element, and a table body was created which will be dynamically added values to.
Just before the closing body tag, a script tag that holds an SRC attribute that holds the path to our JavaScript files was also added, this is because we will be using an external JavaScript file in the building of this project. This is the browser view of the HTML file above.
A bit of CSS styling was added to make things look nice and concise.
Inside the Product_List_App folder, we have created, create a JavaScript file, name it product.js. Inside it is where we will be having all of our algorithms for the Product_List_App.
At this point, your folder should contain the product.html and product.js respectively. Now let us declare all our global variables. Go inside the product.js file we have created to add this;
Going further we will be having eight functions to play around with. These functions will be as follows;
- createItem function,
- totalPrice function,
- tableHead function,
- tableBody function,
- readItem function,
- table function,
- updateItem function,
- deleteItem function.
C- Creating The Products
Now let us head to the createItem function, below the global variable we have created, let us add the createItem function.
Up there, we have declared all of the function variables, the document.querySelector is used to get all there values respectively. Due to our hunt to store all those values and being able to play around with it, the values were set to come out as an object and now push the object into the array we declared in our global variables above.
The createItem function is executed in the create item button in the HTML file we have created.
Now let us head to the browser console to see what the array holds:
Above we first added one item which is milk, the console gave us an array of milk property. Secondly, we added another item which is cornflakes, this time the array holds two instances of an object that holds our items. Going further, this is the way items will continue to be adding into the array.
The total price input holds the multiplication of the quantity value and the price value. If we look closely at the createItem function above, we have just one little challenge here, I guess you may not notice, though it is not a problem if you will be able to be adding the accurate total price of the items your self.
Let me make it clear. Looking at the createItem function above the multiplication of the price and quantity of our items is not automatically set in the total price input, definitely, with that not being fixed we are prone to having a miscalculation of the total price which we don’t want to get involved in at all. Let me save us some stress of going through all that. Quickly, let us add the totalPrice function I mentioned above on the total price input below;
Here, an oninput function was affixed on the price input, it will always lookup on the quantity input to do its calculation and then pass the value to the total price input. This will save us from having to add value to the total price input to avoid miscalculation of the total cost price. Now that we are receiving our values let us move further to save those values.
Saving The Products
This brings us to a powerful browser API called local storage. This gives us the power to store and persist data on our browser. Let us add this to the createItem function created above.
Above, the try and catch method was applied. It is a conditional statement that checks if a given algorithm is correct, if it is not, it catches an error message to the console.
Inside the try curry braces, a conditional statement was used to check if items have been saved to the local storage, if no, the product list will be set to the local storage. If yes the new form data will be added to the existing lists in the local storage. Currently, all of the form data will be saved to the local storage whenever the create item button above is clicked.
If you are following this course, your create item function should look exactly this way below:
Now let us see how our local storage looks currently:
With this above, we have successfully saved some items to the local storage.
On the other hand, any time the create item button is been clicked, it will always submit data to the local storage, whether an empty object or not. So let us move to the createItem function and add some validation before submitting it to the local storage. Below will be added immediately after the const assignments inside the create item function.
Here we have successfully validated the form input data for the product lists. In the above, a check was done to know if the input values are empty, if it is true, an alert will pop up indicating the particular input that was left unfilled and immediately focuses on that input for quick filling of the empty input.
R- Reading the products
This is where we will be displaying our items that will have saved to the local storage on a table we created in the HTML file above. Now let us create the tableHead function that was mentioned above.
The Table Head Function
Above is a function that reads the table headings data that will be soon displayed on the browser. It takes a parameter that lookup for an array of objects to access and consume.
The Object.keys() is a method that gives us the power to the object keys. Read more on objects here. The document.createElement helps us to create dynamic HTML elements. In our case, we used it to create the rows and heading elements of the table. The heading of the table element will hold the keys of the stored objects in the product list array.
The Table Body Function
This is a function that lookup for an array of objects to access as well, just like the table head function we created above, everything remains the same except for the Object.value() method which gives us access to the object values and the cells which will be holding our table body data respectively. Moving further let us create the readItem function that was mentioned above which will display our data so that it will be readable.
Above is a function that displays the data in the local storage for readability. Let us get what just happened here. Firstly a variable named storage was declared to hold the local storage data. Secondly, a check was done to know if the local storage holds any data that will be displayed
Finally, the last check was done to know if the storage data has been loaded to the table. If yes the table remains the same. If no the data will be loaded to the table.
The table head and table body function which was created above was executed inside the readItem function to enable the keys of the data to be the table headings and the values of the data to be the cell values.
The readItem function was triggered on the read item button that was created in the HTML file like so:
Going further, all the yet to create functions will be called in their buttons respectively. Now let us see how our table looks when we fire the read item button
Wow! this is awesome I believe, the read item button got us the product lists displayed on the table. Let us now see and learn how to Update the data that is in the local storage
U- Updating The product Lists
Before updating the table data we should specify the actual item which will be updated. This will make us to now create the table function that was mentioned previously. So let us add the below code to the product.js file:
Up here an on click function was added to the table that was created, the table rows were gotten and assigned to the row that was declared on the screenshot above.
We lopped through the rows of the table to be able to manage each of the row data and finally added an event listener that listens to the click event on each row of the table.
A function was passed as the second parameter of the event listener, which was named activateItem. The function will handle what happens when each row is been clicked. Below let us add the activateItem function;
On the screenshot above, a variable that will hold the index of the activated item when clicked was declared. Because we want to Update the items, the row that was clicked will be set back to the form field for editing.
Now that we have successfully had the activated item back to the form field, next is to now Update the local storage data with our updated item and reload the page.
Previously, we have succeeded in editing the product list when activated for an Update. Above we got the storage data, declared variable that holds the form input values, and declared the table row index variable that holds the index of the item that will be clicked.
Let us go further to validate this form field to make sure that we won’t have to Update an empty string to the local storage and make sure that the user has clicked on the item that will be updated. below let’s Update the updateItem function that was created above with the validations;
Here we have successfully validated the form fields for the product lists. In the above, a check was done to know if a user has activated the item that will be updated, another check was made to check if the input values are empty, if it is true, an alert will pop up indicating the particular input that was left unfilled and immediately focuses on that input for quick filling of the empty input.
After adjusting the form input values, a confirm alert would be good to pop up, why? In case the user remembers to still make some other changes before finally updating the data to the local storage. That privilege will be given to the user. So let us add the alert box in the updateItem function declared above;
Above we have created a window alert box that will always pop up whenever the update item button is been clicked. A text was passed to the confirm parenthesis that holds the message which the user reads and determines if the Update process should continue or cancel the Update process if otherwise.
Now that we have the confirm alert box working like so below;
let us go further to have the edited item updated to the local storage below;
There are a couple of things to notice in the screenshot above, these things are the tableIndexRow and the splice() method that was applied.
Only when confirm is true will the updatedItem function be executed. The splice method is the method that was used to Update the recent change with the old item in the storage.
Note: The Array.filter() can as well be used for data Update in the local storage
The splice method is used to splice the item that is at the same index with the index of the item the user wants to Update. Then the page will be refreshed afterward. Below is what the local storage looks like at this point
Let us Update what we already have in the local storage and see how it works, by adding one more item like bread and updating the cornflakes item to sugar.
This is nice, I believe. let us head to the delete item function to see how things will be done as well.
D- Delete the Product
Many a time in recording, you will wish to have some/a record not being among your recorded list any longer. You will learn that in a blink of an eye and be able to do it your self. Let us quickly create the deleteItem function below;
In the screenshot above, we have created the deleteItem function that was mentioned previously. Inside the deleteItem function, we have a popup that the user has to confirm before deleting any product item from the storage.
We also checked and make sure that the user has activated a particular item, we lopped through the storage to look for the item that is at the same index with the item that was clicked and Delete it from the local storage. Afterward, the page will reload.
Note: Array.find(), Array.Filter(), and include() can also be used to perform the Delete operation.
Let us try out this function by trying to remove the sugar item and leave the storage data with the milk and bread items.
Your HTML file should look like so
Your product.js file should as well look like so;
It was easy right? at least you can now PERSIST and perform CRUD operation with local storage.
If this course was helpful to you you may share and recommend or if you have any problem relating to this course you may as well drop the problems below.
You can follow me up on Medium. Twitter and Linkedin. For this course full code, Here I am