Data Tables

Project Description

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

Setting up the base web page

Your first task is to set up the base web page.

  1. In your portfolio/js folder, create a new sub-folder named data-tables.
  2. Download the following file to this new portfolio/js/data-tables folder.   index.html
  3. Give it the filename index.html.
  4. Update the website logo, favicon, <title> tag and the <footer> with your own details.

This file contains all the necessary HTML and CSS for this project.

Note: Ensure the file is linked to the lunadoge.min.css stylesheet, and not the older lunadoge.css version.

Adding the JavaScript code

At the bottom of your index.html web page, just before the closing </body> tag, add the following JavaScript code within a <script> tag.

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>";
}

Save your file and verify it works correctly.

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