How to create a simple CRUD application using only JavaScript

Posted by severndigital on Mon, 31 Jan 2022 18:27:46 +0100

How to Create a Simple CRUD Application using only JavaScripthttps://www.encodedna.com/javascript/how-to-create-a-simple-crud-application-using-only-javascript.htm

You can use pure JavaScript to create basic single page applications. Today, you can find many comprehensive JavaScript frameworks for building complex front-end applications. I personally used AngularJS and found it very useful. However, for some reason, I still use JavaScript and let me show you how to create a simple CRUD application (single page application) using only JavaScript.

Basic CRUD operations require data. Crud stands for create, read, update and delete, which are the four basic functions of operating data in a database. It can be any database. For my crud application, I use data from JSON objects.

Look at this demo

1) I store data in JSON objects (in my application). I'll extract the data and display it in the Dynamically created HTML tables.

2) There are some in each line Dynamically created HTML elements , such as buttons, text boxes and drop-down lists, are used to perform functions such as update, delete, save, create and cancel.

3) Buttons and text boxes dynamically attach events.

What does this application do?

The application is the Books inventory. It will display a list of different categories of Books with prices. See figure above. This application allows users to view lists, create or add new Books to existing lists (databases), update or edit row data, and delete data (entire rows).

Each transaction affects an array of JSON objects and a temporary database.

Now let's create an application.

Related articles: Use ASP Net to create a simple CRUD application in Angular 6

Tags and CSS and scripts

I have only one DIV element in the < body > section, which will be used as a container. All other elements that I will dynamically create using JavaScript will be attached to this container.

<!DOCTYPE html>
<html>
    <head>
        <title>CRUD Application using JavaScript</title>
        <style>
            table
            {
                width: 100%;
            }
            table, th, td
            {
                border: solid 1px #DDD;
                border-collapse: collapse;
                padding: 2px 3px;
                text-align: center;
            }

            input[type='button']
            {
                cursor: pointer;
                border: none;
                color: #FFF;
            }

            input[type='text'], select
            {
                text-align: center;
                border: solid 1px #CCC;
                width: auto;
                padding: 2px 3px;
            }
        </style>
    </head>
    <body>
        <!--Show the app here.-->
        <div id="container" style="width:700px;"></div>
    </body>

    <script>
        var crudApp = new function () {

            // An array of JSON objects with values.
            this.myBooks = [
                {ID: '1', Book_Name: 'Computer Architecture', Category: 'Computers', Price: 125.60},
                {ID: '2', Book_Name: 'Asp.Net 4 Blue Book', Category: 'Programming', Price: 56.00},
                {ID: '3', Book_Name: 'Popular Science', Category: 'Science', Price: 210.40}
            ]

            this.category = ['Business', 'Computers', 'Programming', 'Science'];
            this.col = [];

            this.createTable = function () {

                // Extract value for table header.
                for (var i = 0; i < this.myBooks.length; i++) {
                    for (var key in this.myBooks[i]) {
                        if (this.col.indexOf(key) === -1) {
                            this.col.push(key);
                        }
                    }
                }

                // CREATE A TABLE.
                var table = document.createElement('table');
                table.setAttribute('id', 'booksTable');     // Seet table id.

                var tr = table.insertRow(-1);               // Create a row (for header).

                for (var h = 0; h < this.col.length; h++) {
                    // Add table header.
                    var th = document.createElement('th');
                    th.innerHTML = this.col[h].replace('_', ' ');
                    tr.appendChild(th);
                }

                // Add rows using JSON data.
                for (var i = 0; i < this.myBooks.length; i++) {

                    tr = table.insertRow(-1);           // Create a new row.

                    for (var j = 0; j < this.col.length; j++) {
                        var tabCell = tr.insertCell(-1);
                        tabCell.innerHTML = this.myBooks[i][this.col[j]];
                    }

                    // Dynamically create and add elements to table cells with events.

                    this.td = document.createElement('td');

                    // *** CANCEL OPTION.
                    tr.appendChild(this.td);
                    var lblCancel = document.createElement('label');
                    lblCancel.innerHTML = '✖';
                    lblCancel.setAttribute('onclick', 'crudApp.Cancel(this)');
                    lblCancel.setAttribute('style', 'display:none;');
                    lblCancel.setAttribute('title', 'Cancel');
                    lblCancel.setAttribute('id', 'lbl' + i);
                    this.td.appendChild(lblCancel);

                    // *** SAVE.
                    tr.appendChild(this.td);
                    var btSave = document.createElement('input');

                    btSave.setAttribute('type', 'button');      // SET ATTRIBUTES.
                    btSave.setAttribute('value', 'Save');
                    btSave.setAttribute('id', 'Save' + i);
                    btSave.setAttribute('style', 'display:none;');
                    btSave.setAttribute('onclick', 'crudApp.Save(this)');       // ADD THE BUTTON's 'onclick' EVENT.
                    this.td.appendChild(btSave);

                    // *** UPDATE.
                    tr.appendChild(this.td);
                    var btUpdate = document.createElement('input');

                    btUpdate.setAttribute('type', 'button');    // SET ATTRIBUTES.
                    btUpdate.setAttribute('value', 'Update');
                    btUpdate.setAttribute('id', 'Edit' + i);
                    btUpdate.setAttribute('style', 'background-color:#44CCEB;');
                    btUpdate.setAttribute('onclick', 'crudApp.Update(this)');   // ADD THE BUTTON's 'onclick' EVENT.
                    this.td.appendChild(btUpdate);

                    // *** DELETE.
                    this.td = document.createElement('th');
                    tr.appendChild(this.td);
                    var btDelete = document.createElement('input');
                    btDelete.setAttribute('type', 'button');    // SET INPUT ATTRIBUTE.
                    btDelete.setAttribute('value', 'Delete');
                    btDelete.setAttribute('style', 'background-color:#ED5650;');
                    btDelete.setAttribute('onclick', 'crudApp.Delete(this)');   // ADD THE BUTTON's 'onclick' EVENT.
                    this.td.appendChild(btDelete);
                }


                // ADD A ROW AT THE END WITH BLANK TEXTBOXES AND A DROPDOWN LIST (FOR NEW ENTRY).

                tr = table.insertRow(-1);           // CREATE THE LAST ROW.

                for (var j = 0; j < this.col.length; j++) {
                    var newCell = tr.insertCell(-1);
                    if (j >= 1) {

                        if (j == 2) {   // WE'LL ADD A DROPDOWN LIST AT THE SECOND COLUMN (FOR Category).

                            var select = document.createElement('select');      // CREATE AND ADD A DROPDOWN LIST.
                            select.innerHTML = '<option value=""></option>';
                            for (k = 0; k < this.category.length; k++) {
                                select.innerHTML = select.innerHTML +
                                        '<option value="' + this.category[k] + '">' + this.category[k] + '</option>';
                            }
                            newCell.appendChild(select);
                        } else {
                            var tBox = document.createElement('input');          // CREATE AND ADD A TEXTBOX.
                            tBox.setAttribute('type', 'text');
                            tBox.setAttribute('value', '');
                            newCell.appendChild(tBox);
                        }
                    }
                }

                this.td = document.createElement('td');
                tr.appendChild(this.td);

                var btNew = document.createElement('input');

                btNew.setAttribute('type', 'button');       // SET ATTRIBUTES.
                btNew.setAttribute('value', 'Create');
                btNew.setAttribute('id', 'New' + i);
                btNew.setAttribute('style', 'background-color:#207DD1;');
                btNew.setAttribute('onclick', 'crudApp.CreateNew(this)');       // ADD THE BUTTON's 'onclick' EVENT.
                this.td.appendChild(btNew);

                var div = document.getElementById('container');
                div.innerHTML = '';
                div.appendChild(table);    // ADD THE TABLE TO THE WEB PAGE.
            };

            // ****** OPERATIONS START.

            // CANCEL.
            this.Cancel = function (oButton) {

                // HIDE THIS BUTTON.
                oButton.setAttribute('style', 'display:none; float:none;');

                var activeRow = oButton.parentNode.parentNode.rowIndex;

                // HIDE THE SAVE BUTTON.
                var btSave = document.getElementById('Save' + (activeRow - 1));
                btSave.setAttribute('style', 'display:none;');

                // SHOW THE UPDATE BUTTON AGAIN.
                var btUpdate = document.getElementById('Edit' + (activeRow - 1));
                btUpdate.setAttribute('style', 'display:block; margin:0 auto; background-color:#44CCEB;');

                var tab = document.getElementById('booksTable').rows[activeRow];

                for (i = 0; i < this.col.length; i++) {
                    var td = tab.getElementsByTagName("td")[i];
                    td.innerHTML = this.myBooks[(activeRow - 1)][this.col[i]];
                }
            }


            // EDIT DATA.
            this.Update = function (oButton) {
                var activeRow = oButton.parentNode.parentNode.rowIndex;
                var tab = document.getElementById('booksTable').rows[activeRow];

                // SHOW A DROPDOWN LIST WITH A LIST OF CATEGORIES.
                for (i = 1; i < 4; i++) {
                    if (i == 2) {
                        var td = tab.getElementsByTagName("td")[i];
                        var ele = document.createElement('select');      // DROPDOWN LIST.
                        ele.innerHTML = '<option value="' + td.innerText + '">' + td.innerText + '</option>';
                        for (k = 0; k < this.category.length; k++) {
                            ele.innerHTML = ele.innerHTML +
                                    '<option value="' + this.category[k] + '">' + this.category[k] + '</option>';
                        }
                        td.innerText = '';
                        td.appendChild(ele);
                    } else {
                        var td = tab.getElementsByTagName("td")[i];
                        var ele = document.createElement('input');      // TEXTBOX.
                        ele.setAttribute('type', 'text');
                        ele.setAttribute('value', td.innerText);
                        td.innerText = '';
                        td.appendChild(ele);
                    }
                }

                var lblCancel = document.getElementById('lbl' + (activeRow - 1));
                lblCancel.setAttribute('style', 'cursor:pointer; display:block; width:20px; float:left; position: absolute;');

                var btSave = document.getElementById('Save' + (activeRow - 1));
                btSave.setAttribute('style', 'display:block; margin-left:30px; float:left; background-color:#2DBF64;');

                // HIDE THIS BUTTON.
                oButton.setAttribute('style', 'display:none;');
            };


            // DELETE DATA.
            this.Delete = function (oButton) {
                var activeRow = oButton.parentNode.parentNode.rowIndex;
                this.myBooks.splice((activeRow - 1), 1);    // DELETE THE ACTIVE ROW.
                this.createTable();                         // REFRESH THE TABLE.
            };

            // SAVE DATA.
            this.Save = function (oButton) {
                var activeRow = oButton.parentNode.parentNode.rowIndex;
                var tab = document.getElementById('booksTable').rows[activeRow];

                // UPDATE myBooks ARRAY WITH VALUES.
                for (i = 1; i < this.col.length; i++) {
                    var td = tab.getElementsByTagName("td")[i];
                    if (td.childNodes[0].getAttribute('type') == 'text' || td.childNodes[0].tagName == 'SELECT') {  // CHECK IF ELEMENT IS A TEXTBOX OR SELECT.
                        this.myBooks[(activeRow - 1)][this.col[i]] = td.childNodes[0].value;      // SAVE THE VALUE.
                    }
                }
                this.createTable();     // REFRESH THE TABLE.
            }

            // CREATE NEW.
            this.CreateNew = function (oButton) {
                var activeRow = oButton.parentNode.parentNode.rowIndex;
                var tab = document.getElementById('booksTable').rows[activeRow];
                var obj = {};

                // ADD NEW VALUE TO myBooks ARRAY.
                for (i = 1; i < this.col.length; i++) {
                    var td = tab.getElementsByTagName("td")[i];
                    if (td.childNodes[0].getAttribute('type') == 'text' || td.childNodes[0].tagName == 'SELECT') {      // CHECK IF ELEMENT IS A TEXTBOX OR SELECT.
                        var txtVal = td.childNodes[0].value;
                        if (txtVal != '') {
                            obj[this.col[i]] = txtVal.trim();
                        } else {
                            obj = '';
                            alert('all fields are compulsory');
                            break;
                        }
                    }
                }
                obj[this.col[0]] = this.myBooks.length + 1;     // NEW ID.

                if (Object.keys(obj).length > 0) {      // CHECK IF OBJECT IS NOT EMPTY.
                    this.myBooks.push(obj);             // PUSH (ADD) DATA TO THE JSON ARRAY.
                    this.createTable();                 // REFRESH THE TABLE.
                }
            }

            // ****** OPERATIONS END.
        }

        crudApp.createTable();
    </script>
</html>
have a try

I have a global function called crudApp(), which has other functions to make CRUD operations work.

First, I declare an array of JSON objects with values in myBooks. This is my data and I will use it.

Here myBooks = [];

I have another array of JSON objects called category. I'll use the category object to populate the SELECT drop-down list and add it to each row of the table.

The list (or data) is displayed in an HTML table. Since I did not include table elements in the design pattern, I will Creating tables dynamically using JSON data . To do this, I declare a function called createTable().

this.createTable = function () {}

Dynamically create HTML tables

1) The for loop extracts the value of the header from the array myBooks and stores it in another array named col []. I use this array in many functions in this application.

2) When I create the table, I am dynamically adding (or attaching) some elements to each row of the table.

The first element is the display ✖  (lblCancel.innerHTML = ' ✖') Label of the symbol. This tab functions like a button to cancel. Clicking this element will cancel the update function. Therefore, it attaches the onclick event, which calls a function called Cancel().

lblCancel.setAttribute('onclick', 'crudApp.Cancel(this)');

Similarly, I'm creating and adding three buttons with events and IDS (input elements of button types). Each has the functions of saving, updating and deleting.

You can use the setAttribute() method to add additional functionality.

3) Finally, I complete the table creation section by adding a row at the end of the table. The row has two blank text boxes and a SELECT drop-down list, and the last column has a button (create). This is to create new data for the list.

Function of CRUD operation

I have five different functions to perform different operations. These functions are

1) this. Cancel () - this cancels the update process. Each row of the table has an update button. Clicking this button will display two other buttons, cancel and save. Clicking the Cancel button will call the function this Cancel(), which takes the parameter as the calling element.

Using references to objects, you can get the active row, its elements, and values.

2) this.Update() – this function is called when you click the update button on any line. It displays only input elements, such as text boxes and drop-down lists with values. So now you can edit the value in each cell of the selected row (except the first column).

In addition, it will display ✖ Button (cancel) and save button. Look at the picture.

3) this.Delete() - this function uses JavaScript splice() method Delete data from JSON array.

this.myBooks.splice((activeRow - 1), 1);

splice() usually takes three parameters to explain as follows . I provided two. The first parameter is the position in the array (which is why I use activeRow - 1), and I want to delete it. The second parameter is the number of items I want to delete from the array (I have 1). Add a value of 2 to see what happens.

4) this.Save() - this function will update or save the row data in the array. It is associated with an update operation. The Save option is activated when the user clicks the update button in any row.

5) this.Create() – the last row has a blank box and the last column has a button named create. Clicking the Create button will call this function and add a new set of data to the existing list in the myBooks array.

Look at this demo

It is a very basic application. You can add more features. The purpose of sharing this example is to show how easily you can create a basic CRUD application using only JavaScript without using any JS framework.

The data I use in this application is a JSON array, a temporary data source. You can use a more dynamic database, such as SQL Server, and use Web API methods to manipulate data.

The Ajax # XMLHttpRequest object is another option for API calls in JavaScript. This is what you might use in this application Examples of.

Topics: Javascript Front-end