I am using HBS template engine, with Nodejs and Mysql backend, I have created a view to display the MySQL table data along with edit buttons which opens the corresponding popup boxes for each data with the option to edit them in frontend

I have a mysql table named groups which has some data, i want to change the data dynamically in my webpage. For that i have added some javascript validations

To add validation, I am using fetch request in frontend javascript to make a call to the server and display the notification alert as a part of validation process. for eg: The Group Name already exists Since getElementById selects only first element for the fetch request, I would really appreciate if anyone can tell me how to send all the corresponding element's values when their popup's submit buttons are clicked. In short, the code only works for the first data in the table and not for other rows. Here is the javascript code

console.log("Inside edit group js")
document.addEventListener('DOMContentLoaded', function () {
   console.log("DOM loaded")
// Getting Edit Contact Modal
let editGroupModal = document.getElementsByClassName("editGroupModal");
let editGroupModalContent = document.getElementsByClassName("editGroupModalContent");
let editGroupBtn = Array.from(document.getElementsByClassName("editGroupBtn"));


const groupNameTable = Array.from(document.getElementsByClassName('tableFirstName'));
console.log(groupNameTable);
// let groupNameInput = document.getElementsByClassName("firstName");
const editGroupClose = Array.from(document.getElementsByClassName("editGroupClose"));

for (let i = 0; i < editGroupBtn.length; i++) {

    // const closeEditContact = document.getElementsByClassName("close");

    editGroupBtn[i].onclick = function () {
        editGroupModal[i].style.display = "block"

    }
}

// Closing Btn

for (let i = 0; i < editGroupClose.length; i++) {

    editGroupClose[i].onclick = function () {
        console.log("INSIDE MAINFRAME!")
        console.log(editGroupModal[i])
        editGroupModal[i].style.display = "none";

    }
}

// Validation

// Real Start

console.log("Inside Real Start")
const editGroupForm = document.getElementById('editGroupForm');
const editGroupErrorBox = document.getElementById('editGroupErrorBox');
const editGroupSuccessBox = document.getElementById('editGroupSuccessBox');
console.log("Before Display error function");

function displayError(errorMessage) {
    // Display the error message in the common error box'
    editGroupErrorBox.style.backgroundColor = "lightcoral";
    editGroupErrorBox.style.padding = '1.2rem';
    editGroupErrorBox.style.margin = '0.8rem';
    editGroupErrorBox.textContent += errorMessage + '\n';
    editGroupErrorBox.style.display = 'block';
}

function displaySuccess(successMsg) {
    // Display the error message in the common error box'

    console.log("justleftdisplays-function");

    editGroupSuccessBox.style.backgroundColor = "lightgreen";
    editGroupSuccessBox.style.padding = '1.2rem';
    editGroupSuccessBox.style.margin = '0.8rem';
    editGroupSuccessBox.textContent += successMsg + '\n';
    editGroupSuccessBox.style.display = 'block';

  }

  editGroupForm.addEventListener('submit', async function (event) {
    event.preventDefault();

    console.log("Inside event listener");

    editGroupErrorBox.textContent = '';
    editGroupErrorBox.style.display = 'none';

    const editGroupInputs = document.querySelector('.updatedGroupNameClass');
    const updatedGroupIdInput = document.querySelector('.updatedGroupIdsClass');
    console.log(editGroupInputs);

    const editGroupInput = document.getElementById(`editGroupNameInputId`).value; //use this in fetch
    const editGroupId = document.getElementById('updatedGroupId').value;

    try {
        const editGroupResponse = await fetch('/pbEditGroup', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                updatedGroupName:editGroupInput,
                updatedGroupId: editGroupId
            }),
        });

 

        const editGroupData = await editGroupResponse.json();
     

        if (editGroupData.affectedRows === 1) {
            console.log("Data has been saved");
            displaySuccess("Data has been saved");
            setTimeout(async function () {
                // Form submit after 1 second
                await editGroupForm.submit();
              }, 5000);
            
        }

        else {
            console.log("Data already exists");
            displayError("Data already exists");
            setTimeout(async function () {
                // Form submit after 1 second
                await editGroupForm.submit();
              }, 5000);
        } 
    } catch (error) {
        console.error("An error occurred:", error);
    }

});
});

Here is the backend NodeJs code

  // Edit Groups - Group Management

router.post("/pbEditGroup", async function(req,res){

    const updatedGroupName   = await req.body.updatedGroupName;
    console.log(updatedGroupName)
    let updatedGroupId = await req.body.updatedGroupId;
    console.log(updatedGroupId);

    const query = "UPDATE `groups` SET groupName = ? WHERE groupId = ?";
    // const query = "SELECT COUNT(*) AS count FROM `groups` WHERE phoneNumber = ? AND groupId !=?"

db.query(query, [updatedGroupName, updatedGroupId], async function (error, results) {
    if (error) {
        console.error(error);
        res.json(error)
    } 
    else {
     
        // results?console.log(success):console.log("Moye Moye");
        // console.log(results)
        res.json(results)
      
       

    }
});
})

Here is the frontend html/hbs code

  <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/css/global.css">
    <link rel="stylesheet" href="/css/phonebook.css">
    <link rel="stylesheet" href="/css/phonebook/groupmg.css">
    <title>Group Management : Phonebook </title>
</head>

<body>
    {{>header2}}

    <!-- Left Sidebar -->
    <div class="sidebar-wrapper">

        <!-- Sidebar Links -->

        <ul class="sidebar">
            <li class="tab-heading active"><a href="http://localhost/designsoft/">Home</a></li>
            <li class="tab-heading"> Contacts </li>
            <li class="tab-heading img-invert"><a href="/phonebook"> Local Phonebook </a></li>
            <li class="tab-heading img-invert">Group Management</li>
            <li class="tab-heading img-invert"> Phonebook Management</li>


        </ul>
    </div>

    <div class="container">

        <div class="title-wrap">
            <h1> Group Management </h1>

            {{error.sqlMessage}} {{success}}


            <div class="filters">
                <div>

                    <button class="btn-narrow" id="groupmg-popup-btn">Group Management</button>
                    <button class="btn-white" id="pbGroupFiltersBtn"> <img src="img/vectors/filters.svg" height="10px"
                            width="10px"> Filters </button>

                </div>

            </div>
        </div>

        {{!-- Main Content --}}

        <section class="table-container" style="margin-top: 10px;">
            <table class="table" id="phonebookTable">
                <thead class="table-header">
                    <tr>
                        <td> Id </td>
                        <td> Group Name </td>
                 
                    </tr>
                </thead>
                <tbody>
                    {{#each groupData}}
                    <tr class="pbtBody">
                        <td class="tableId"> {{this.groupId}} </td>
                        <td class="tableFirstName groupNameData" value=""> {{this.groupName}} </td>

                        <td>
                            <button class="btn-narrow editGroupBtn"> Edit Group </button>
                        </td>
                    </tr>
                    {{/each}}
                </tbody>
            </table>
        </section>

        <button class="btn" id="addGroupBtn"> Add Group</button>

        <div id="addGroupModal" class="modal">

            <!-- Modal content -->
            <div class="modal-content">
                <div class="modal-header">
                    <h2> Add Group </h2>
                    <span id="groupClose" style="cursor:pointer"> Close &times;</span>
                </div>
                <div class="modal-body">

                    <form class="form-flex-ac" id="addGroupForm" action="/pbAddGroup" method="POST">
                    <label> Enter Group Name </label>
                    <input type="text" placeholder="Enter Group Name" name="groupName" id="addGroupNameInputId" required>
                    <button class="btn" id="addGroupSubmitButton" type="submit"> Add Group </button>

                    </form>
                    <div class="notification-wrapper">
                        <span id="commonErrorBox"></span>
                        <span id="addGroupErrorBox"></span>
                        <span id="addGroupSuccessBox"></span>
                    </div>

                </div>
                <div class="modal-footer">
                    {{!-- <h3>Modal Footer</h3> --}}
                </div>
            </div>

        </div>

        {{!-- Edit Group Modal --}}

        {{#each groupData}}

             <div id="editGroupModal" class="modal editGroupModal">

            <!-- Modal content -->
            <div class="modal-content editGroupModalContent">
                <div class="modal-header">
                    <h2> Edit Group </h2>
                    <span class="editGroupClose" style="cursor:pointer"> Close &times;</span>
                </div>
                <div class="modal-body">

                    <form class="form-flex-ac" id="editGroupForm" action="/pbEditGroup" method="POST">
                    <label> Group Id </label>
                    <input type="number" class="updatedGroupIdsClass" name="updatedGroupId" id="updatedGroupId" value="{{this.groupId}}" required>
                    <label> Edit Group Name</label>
                    <input type="text" class="updatedGroupNameClass" placeholder="Edit Group Name" name="updatedGroupName" id="editGroupNameInputId" value="{{this.groupName}}" required>
                    <button class="btn" id="editGroupSubmitButton" type="submit"> Edit Group </button>

                    </form>
                    <div class="notification-wrapper">
                        <span id="commonErrorBox"></span>
                        <span id="editGroupErrorBox"></span>
                        <span id="editGroupSuccessBox"></span>
                    </div>

                </div>
                <div class="modal-footer">
                    {{!-- <h3>Modal Footer</h3> --}}
                </div>
            </div>

        </div>

           {{/each}}

        <script src="/js/phonebook/groupMng/groupmg.js"></script>
        <script src="/js/phonebook/groupMng/addGroups.js"></script>
        <script src="/js/phonebook/groupMng/editGroup.js"></script>

</body>

</html>

Any help would be greatly appreciated, thank you so much!!

0

There are 0 best solutions below