Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptEmployee Database Management System using HTML CSS and JavaScript

Employee Database Management System using HTML CSS and JavaScript

In this article, we will be building an employee database management system using JavaScript.

Employee Database Management System is the collection of Employees’ data like names, first and last, email, contact numbers, salary and date of birth, etc. It provides an easy way to access and manage the list of employees in one place. A new employee can be added with valid details along with optional image src given in the add form and can also be removed from the database.

On completion, it will look like:

Screenshot-from-2023-08-08-13-28-42

Approach

  • First create a sample database with employee data like first name, last name, email, contact number, date of birth, salary and optional profile pic and store all in the data.json file as shown below in code.
  • Create a basic webpage structure with html and the data in the data.json file to show dummy html page using title and add employee button in header tag, form and inputs to get the new user data and divs, spans to display the employee data along with the relevent classes and ids.
  • Style the webpage with CSS properties using class names, ids and elements with properties like box-sizing, margin, padding , background color, display, curser, border, font-family, hower, overflow etc.
  • Using JavaScript get all date from data.json file using fetch() functiona and render it to the webpage using HTML dom methods.
  • Use addEventListener method to add click event to the add employee button and link it with callback function that takes userinput and add new employee data to the database and rerender all data on the page using renderemployees function.
  • Define a function named renderSingleEmployee that takes employee id and display all data on the side.
  • Link click event to the cross sign to delete that specific employee data from the database using deleteEmployee function with array.filter method.

 

Example:

Javascript




(async function () {
    const data = await fetch("data.json");
    const res = await data.json();
  
    let employees = res;
    let selectedEmployeeId = employees[0].id;
    let selectedEmployee = employees[0];
  
    const employeeList = document.querySelector(
        ".employees__names--list"
    );
    const employeeInfo = document.querySelector(
        ".employees__single--info"
    );
  
    // Add Employee - START
    const createEmployee = document.querySelector(
        ".createEmployee"
    );
    const addEmployeeModal =
        document.querySelector(".addEmployee");
    const addEmployeeForm = document.querySelector(
        ".addEmployee_create"
    );
  
    createEmployee.addEventListener("click", () => {
        addEmployeeModal.style.display = "flex";
    });
  
    addEmployeeModal.addEventListener("click", (e) => {
        if (e.target.className === "addEmployee") {
            addEmployeeModal.style.display = "none";
        }
    });
  
    // Set Employee age to be entered minimum 18 years
    const dobInput = document.querySelector(
        ".addEmployee_create--dob"
    );
    dobInput.max = `${
        new Date().getFullYear() - 18
    }-${new Date().toISOString().slice(5, 10)}`;
  
    addEmployeeForm.addEventListener("submit", (e) => {
        e.preventDefault();
        const formData = new FormData(addEmployeeForm);
        const values = [...formData.entries()];
        let empData = {};
        values.forEach((val) => {
            empData[val[0]] = val[1];
        });
        empData.id = employees[employees.length - 1].id + 1;
        empData.age =
            new Date().getFullYear() -
            parseInt(empData.dob.slice(0, 4), 10);
        empData.imageUrl =
            empData.imageUrl ||
"gfg.png";
        employees.push(empData);
        renderEmployees();
        addEmployeeForm.reset();
        addEmployeeModal.style.display = "none";
    });
    // Add Employee - END
  
    // Select Employee Logic - START
    employeeList.addEventListener("click", (e) => {
        if (
            e.target.tagName === "SPAN" &&
            selectedEmployeeId !== e.target.id
        ) {
            selectedEmployeeId = e.target.id;
            renderEmployees();
            renderSingleEmployee();
        }
        // Employee Delete Logic - START
        if (e.target.tagName === "I") {
            employees = employees.filter(
                (emp) =>
                    String(emp.id) !==
                    e.target.parentNode.id
            );
            if (
                String(selectedEmployeeId) ===
                e.target.parentNode.id
            ) {
                selectedEmployeeId = employees[0]?.id || -1;
                selectedEmployee = employees[0] || {};
                renderSingleEmployee();
            }
            renderEmployees();
        }
        // Employee Delete Logic - END
    });
    // Select Employee Logic - END
  
    // Render All Employees Logic - START
    const renderEmployees = () => {
        employeeList.innerHTML = "";
        employees.forEach((emp) => {
            const employee = document.createElement("span");
            employee.classList.add(
                "employees__names--item"
            );
            if (
                parseInt(selectedEmployeeId, 10) === emp.id
            ) {
                employee.classList.add("selected");
                selectedEmployee = emp;
            }
            employee.setAttribute("id", emp.id);
            employee.innerHTML = `${emp.firstName} ${emp.lastName} 
                <i class="employeeDelete">&#10060;</i>`;
            employeeList.append(employee);
        });
    };
    // Render All Employees Logic - END
  
    // Render Single Employee Logic - START
    const renderSingleEmployee = () => {
        // Employee Delete Logic - START
        if (selectedEmployeeId === -1) {
            employeeInfo.innerHTML = "";
            return;
        }
        // Employee Delete Logic - END
  
        employeeInfo.innerHTML = `
        <img src="${selectedEmployee.imageUrl}" />
        <span class="employees__single--heading">
        ${selectedEmployee.firstName} ${selectedEmployee.lastName} 
            (${selectedEmployee.age})
        </span>
        <span>${selectedEmployee.address}</span>
        <span>${selectedEmployee.email}</span>
        <span>Mobile - ${selectedEmployee.contactNumber}</span>
        <span>DOB - ${selectedEmployee.dob}</span>
      `;
    };
    // Render Single Employee Logic - END
  
    renderEmployees();
    if (selectedEmployee) renderSingleEmployee();
})();


Javascript




// data.json
[
    {
        "id": 1001,
        "imageUrl": "gfg.png",
        "firstName": "Thomas",
        "lastName": "Leannon",
        "email": "Thomas.Leannon@gfg.com",
        "contactNumber": "4121091095",
        "age": 43,
        "dob": "26/08/1979",
        "salary": 1,
        "address": "Address1"
    },
    {
        "id": 1002,
        "imageUrl": "gfg.png",
        "firstName": "Faye",
        "lastName": "Sauer",
        "email": "Faye.Sauergfg.com",
        "contactNumber": "4914696673",
        "age": 60,
        "dob": "28/06/1962",
        "salary": 2,
        "address": "Address2"
    },
    {
        "id": 1003,
        "imageUrl": "gfg.png",
        "firstName": "Deven",
        "lastName": "Halvorson",
        "email": "Deven.Halvorsongfg.com",
        "contactNumber": "4479795571",
        "age": 29,
        "dob": "06/01/1993",
        "salary": 3,
        "address": "Address3"
    },
    {
        "id": 1004,
        "imageUrl": "gfg.png",
        "firstName": "Melisa",
        "lastName": "Schuppe",
        "email": "Melisa.Schuppegfg.com",
        "contactNumber": "4443995334",
        "age": 38,
        "dob": "06/09/1984",
        "salary": 4,
        "address": "Address4"
    },
    {
        "id": 1005,
        "imageUrl": "gfg.png",
        "firstName": "Dell",
        "lastName": "Kris",
        "email": "Dell.Krisgfg.com",
        "contactNumber": "4505692843",
        "age": 89,
        "dob": "14/03/1933",
        "salary": 5,
        "address": "Address5"
    },
    {
        "id": 1006,
        "imageUrl": "gfg.png",
        "firstName": "Marcia",
        "lastName": "Gutmann",
        "email": "Marcia.Gutmanngfg.com",
        "contactNumber": "4746199430",
        "age": 56,
        "dob": "24/07/1966",
        "salary": 6,
        "address": "Address6"
    },
    {
        "id": 1007,
        "imageUrl": "gfg.png",
        "firstName": "Jarrod",
        "lastName": "Ortiz",
        "email": "Jarrod.Ortizgfg.com",
        "contactNumber": "4859095720",
        "age": 82,
        "dob": "26/12/1940",
        "salary": 7,
        "address": "Address7"
    },
    {
        "id": 1008,
        "imageUrl": "gfg.png",
        "firstName": "Gabriella",
        "lastName": "Wilkinson",
        "email": "Gabriella.Wilkinsongfg.com",
        "contactNumber": "4379190775",
        "age": 36,
        "dob": "24/06/1986",
        "salary": 8,
        "address": "Address8"
    },
    {
        "id": 1009,
        "imageUrl": "gfg.png",
        "firstName": "Elisabeth",
        "lastName": "Hayes",
        "email": "Elisabeth.Hayesgfg.com",
        "contactNumber": "4394091994",
        "age": 66,
        "dob": "17/08/1956",
        "salary": 9,
        "address": "Address9"
    },
    {
        "id": 1010,
        "imageUrl": "gfg.png",
        "firstName": "Jaime",
        "lastName": "Reichel",
        "email": "Jaime.Reichelgfg.com",
        "contactNumber": "4622392580",
        "age": 41,
        "dob": "21/01/1981",
        "salary": 10,
        "address": "Address10"
    }
]


HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Employee Database Management System</title>
</head>
  
<body>
    <div id="app">
        <header class="header">
            <h1>Employee Database Management</h1>
            <button class="createEmployee">
                Add Employee
            </button>
        </header>
  
        <div class="employees">
            <div class="employees__names">
                <span class="employees__names--title">
                      Employee List
                  </span>
                <div class="employees__names--list"></div>
            </div>
            <div class="employees__single">
                <div class="employees__single--title">
                    Employee Information
                </div>
                <div class="employees__single--info"></div>
            </div>
        </div>
        <!-- Add Employee Code - START -->
        <div class="addEmployee">
            <form class="addEmployee_create">
                Add a new Employee
                <div>
                    <input type="text" name="firstName" 
                           placeholder="First Name" required />
                    <input type="text" name="lastName" 
                           placeholder="Last Name" required />
                </div>
                <input type="text" name="imageUrl" 
                       placeholder="Image URL (Optional)" />
                <input type="email" name="email" 
                       placeholder="Email" required />
                <input type="number" name="contactNumber" 
                       placeholder="Contact" required />
                <input type="number" name="salary" 
                       placeholder="Salary" required />
                <input type="text" name="address" 
                       placeholder="Address" required />
                <input type="date" name="dob" 
                       placeholder="Date of Birth" 
                       class="addEmployee_create--dob" 
                       required />
                <input type="submit" 
                       class="addEmployee_create--submit" 
                       value="Submit" />
            </form>
        </div>
        <!-- Add Employee Code - END -->
    </div>
  
    <script src="script.js"></script>
</body>
  
</html>


CSS




/* Initial Structural CSS - START */
:root {
    --btn: #dbdbdb;
    --btn-hover: #cacaca;
    --item-bg: #f0f0f0;
    --modal-bg: rgba(141, 141, 141, 0.541);
}
body {
    font-family: sans-serif;
    padding: 0 10px;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.header > button {
    padding: 10px 15px;
    border-radius: 20px;
    border: none;
    background-color: var(--btn);
    cursor: pointer;
}
.header > button:hover {
    background-color: var(--btn-hover);
}
.employees {
    display: flex;
}
.employees > div {
    border: 1px solid black;
    overflow-y: scroll;
    height: 450px;
}
.employees__names {
    width: 30%;
}
.employees__single {
    width: 70%;
}
.employees__names,
.employees__single {
    padding: 10px;
    display: flex;
    flex-direction: column;
}
.employees__names--title,
.employees__single--title {
    padding-bottom: 10px;
    margin-bottom: 5px;
    text-align: center;
    border-bottom: 1px solid black;
}
/* Initial Structural CSS - END */
  
/* Render all Employees - START */
.employees__names--list {
    display: flex;
    flex-direction: column;
}
.employees__names--item {
    cursor: pointer;
    padding: 10px 15px;
    margin-bottom: 5px;
    text-align: center;
    background-color: var(--item-bg);
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.employees__names--item:hover,
.selected {
    background-color: var(--btn);
}
/* Render all Employees - END */
  
/* Render Single Employee - START */
.employees__single--heading {
    text-align: center;
    font-size: 25px;
    text-transform: uppercase;
    padding: 5px;
}
.employees__single--info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}
.employees__single--info > img {
    width: 250px;
    height: 250px;
    object-fit: contain;
    border-radius: 50%;
}
/* Render Single Employee - END */
  
/* Add Employee - START */
.addEmployee {
    display: none;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    justify-content: center;
    align-items: center;
    background-color: var(--modal-bg);
}
.addEmployee_create {
    width: 400px;
    background-color: white;
    box-shadow: 0 0 50px grey;
    padding: 20px;
    border-radius: 5px;
    text-align: center;
    display: flex;
    flex-direction: column;
    gap: 15px;
}
.addEmployee_create > div {
    display: grid;
    grid-template-columns: 48.1% 48.1%;
    column-gap: 15px;
}
.addEmployee_create input {
    padding: 5px 10px;
    border-radius: 5px;
    border: 1px solid rgb(236, 236, 236);
}
  
/* removes arrows from input type='number' */
.addEmployee_create input::-webkit-outer-spin-button,
.addEmployee_create input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
.addEmployee_create--submit {
    padding: 10px !important;
    border-radius: 5px;
    border: none;
    background-color: var(--btn);
    cursor: pointer;
}
.addEmployee_create--submit:hover {
    background-color: var(--btn-hover);
}
/* Add Employee - END */


Output:

Peek-2023-08-08-13-35

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments