Многократное отображение таблицы при нажатии кнопки «Добавить» с использованием JavaScript - PullRequest
1 голос
/ 23 октября 2019

При нажатии кнопки я хочу добавить значения текстового поля в массив и отобразить обновленную таблицу только с использованием JavaScript. Написали код, но при многократных добавлениях таблица отображается несколько раз. Я проверяю, включая идентификатор таблицы в качестве условия, но она не работает. Я новичок в программировании и JavaScript, не могли бы вы помочь мне с этим.

Я не могу понять, почему таблица снова заполняется при добавлении Кнопка Какие условия я должен включить, чтобы избежать этого

/*eslint-env browser*/
var $ = function (id) {
    "use strict";
    return window.document.getElementById(id);
};

// Intitial Employee List
var employeeList = [["Sally Smith", "Quality Assurance", 3423], ["Mark Martin", "VP Sales", 3346], ["John Jognson", "Marketing", 3232], ["Windy Smith", "Software Engineer", 4590], ["Jacob Williams", "Technical Architect", 9090]];


function getNumberOfEmployees() {
 "use strict";
 return "Showing " + employeeList.length + " Employees";
}

function validateEmployee() {
    // Validation code
    return isValidEmployee;
}

function addNewEmployee() {
    "use strict";
    var name, title, extension;
    name = $("empName").value;
    title = $("empTitle").value;
    extension = $("empExtension").value;
    employeeList.push([name, title, extension]);
    return employeeList;
}

function displayEmployeeDetails() {
    "use strict";
    var i, index, table, employeeTable, tableRow, tableHeader, nameHeader, titleHeader, extensionHeader, nameTd, nameData, titleTd, titleData, extensionTd, extensionData, employeeList, deleteTd, deleteBtn;
    employeeList = addNewEmployee();

    if (employeeList.length !== 0) {
        $("showEmployees_header").innerHTML = getNumberOfEmployees();
        //Creating the HTML Table 
        employeeTable = window.document.createElement("table");
        employeeTable.setAttribute("id", "employeeTable");

        //Adding the Table row for the Headers
        tableRow = window.document.createElement("tr");
        employeeTable.appendChild(tableRow);

        //Adding the Table Headers
        tableHeader = window.document.createElement("th");
        nameHeader = window.document.createTextNode("Name");
        tableHeader.appendChild(nameHeader);
        tableRow.appendChild(tableHeader);

        tableHeader = window.document.createElement("th");
        titleHeader = window.document.createTextNode("Title");
        tableHeader.appendChild(titleHeader);
        tableRow.appendChild(tableHeader);


        tableHeader = window.document.createElement("th");
        extensionHeader = window.document.createTextNode("Extension");
        tableHeader.appendChild(extensionHeader);
        tableRow.appendChild(tableHeader);

        window.document.body.appendChild(employeeTable);
        for (i = 0; i < employeeList.length; i += 1) {
            //Adding a row to the Table for each Employee details
            tableRow = window.document.createElement("tr");

            //Creating 3 Tds for the Name, Title and Extension
            nameTd = window.document.createElement("td");
            nameData = window.document.createTextNode(employeeList[i][0]);
            nameTd.appendChild(nameData);
            tableRow.appendChild(nameTd);

            titleTd = window.document.createElement("td");
            titleData = window.document.createTextNode(employeeList[i][1]);
            titleTd.appendChild(titleData);
            tableRow.appendChild(titleTd);

            extensionTd = window.document.createElement("td");
            extensionData = window.document.createTextNode(employeeList[i][2]);
            extensionTd.appendChild(extensionData);
            tableRow.appendChild(extensionTd);

            deleteTd = window.document.createElement("td");
            deleteBtn = window.document.createElement("input");
            deleteBtn.type = "button";
            deleteBtn.value = "delete";
            deleteBtn.id =  i;
            deleteBtn.addEventListener("click", function () {
                index = this.closest('tr').rowIndex;
                window.console.log(index);
                table = $('employeeTable');
                table.deleteRow(index);
                employeeList.splice(index - 1, 1);
                window.console.log(employeeList);
                $("showEmployees_header").innerHTML = getNumberOfEmployees();
            });
            deleteTd.appendChild(deleteBtn);
            tableRow.appendChild(deleteTd);

            employeeTable.appendChild(tableRow);
        }
    }
}

function processEmployee() {
    "use strict";
    if (validateEmployee()) {
        window.console.log("Valid Employee");
        displayEmployeeDetails();
    }
}

var resetForm = function () {
        "use strict";
        $("employeeForm").reset();
        $("empName").focus();
    };

window.addEventListener("load", function () {
    "use strict";
    $("btnAdd").addEventListener("click", processEmployee);
    $("btnReset").addEventListener("click", resetForm);
    $("empName").focus();
    if (employeeList.length === 0) {
        $("showEmployees_header").display("none");
        $("employeeDetails").display("none");
    }
});
...