Data Tables

Project Description

Populates an HTML table with data stored in an array. Includes the option to remove data items.

You can view a completed version of the project here.

Your project folder

In your portfolio/js folder is a folder named data-tables that contains all the files you need for this JavaScript project.

In VS Code, open the project’s index.html web page and ensure the hyperlinks and personal details have been correctly updated.

Adding the JavaScript code

Follow the steps below to add the JavaScript code to the index.html file.

  1. Scroll down the web page until you see an empty pair of opening <script> and closing </script> tags.
  2. Click inside the empty pair of tags and paste the JavaScript code below.
    let all_btns = document.querySelectorAll('#myTable .btn');
    
    all_btns.forEach(el => el.addEventListener('click', event => {
       event.preventDefault();
       // get button id
       btn_id = event.currentTarget.id;
       deleteRow(btn_id);
    }));
    
    
    function deleteRow(btn_id) {
       const rows = document.querySelectorAll("#myTable tr");
       for (let i = rows.length; i--;) {
          if(rows[i].innerHTML.includes(btn_id)) {
             rows[i].parentNode.removeChild(rows[i]);
          }
       }
    }
    
    const arrStudentData = [
       {id: "1224", firstname: "John", lastname: "Smith"},
       {id: "5678", firstname: "Jane", lastname: "Higgins"},
       {id: "1717", firstname: "Frank", lastname: "Jones"},
       {id: "2121", firstname: "Mary", lastname: "Dwyer"}
    ];
    
    function populateTable(){
       let tableContent = "";
       let delBtn = "<a class=\"btn\" onclick=\"deleteRow(this)\"><i class=\"fa-solid fa-trash-can\"></i>Delete</a>";
          for(var i in arrStudentData){
             tableContent += "<tr>";
             tableContent += "<td>" + arrStudentData[i].id +"</td>"
                + "<td>" + arrStudentData[i].firstname +"</td>"
                + "<td>" + arrStudentData[i].lastname +"</td>"
                + "<td><a class=\"btn\" onclick=\"deleteRow("+arrStudentData[i].id+")\"><i class=\"fa-solid fa-trash-can\"></i>Delete</a></td>";
                tableContent += "</tr>";
           }
    
       document.getElementById("studentData").innerHTML = tableContent;
       document.getElementById("btn_populate").innerHTML = "Refresh Table <i class=\"fa-solid fa-circle-plus\"></i>";
    }
  3. Save your index.html file.
  4. Display the file in a web browser and verify it works correctly.

Uploading your project to GitHub

Upload the data-tables folder as a sub-folder of the portfolio/js folder on your GitHub account.