skip to Main Content
function deleteClient(i) {
    let confirmation ="";
    
    notificationParent.classList.add("active");
    
    notificationBtn.forEach((btn) => {
        btn.addEventListener("click", () => {
            confirmation = btn.dataset.content // ok or cancel
            
            if(confirmation == "ok"){
                clientsArray.splice(i, 1);
                localStorage.Clients = JSON.stringify(clientsArray);
                notificationParent.classList.remove("active");
            }else{
                notificationParent.classList.remove("active");
            }
        })
    })
    
    showClientsData();
}

Each time I click the button it delete delete all index

I tried many approaches but the result was the same

2

Answers


  1. you can move the event listener outside the loop this should prevent this behavior

    function deleteClient(i) {
        let confirmation = "";
    
        notificationParent.classList.add("active");
    
        function handleButtonClick(btn) {
            confirmation = btn.dataset.content; // ok or cancel
    
            if (confirmation === "ok") {
                clientsArray.splice(i, 1);
                localStorage.Clients = JSON.stringify(clientsArray);
            }
    
            notificationParent.classList.remove("active");
            showClientsData();
        }
    
        notificationBtn.forEach((btn) => {
            btn.addEventListener("click", () => handleButtonClick(btn));
        });
    }
    
    Login or Signup to reply.
  2. The issue is that in your deleteClient function, every time it is called, it adds new event listeners to notificationBtn. Thus if you click the button multiple times, multiple event listeners are added, and they all get triggered for a single click event, leading to the deletion of multiple indexes.

    // Assuming notificationBtn is a collection of your buttons
    let deleteIndex = null; // Variable to store the index to be deleted
    
    // Setup event listeners once
    notificationBtn.forEach((btn) => {
        btn.addEventListener("click", () => {
            let confirmation = btn.dataset.content; // ok or cancel
    
            if (confirmation === "ok" && deleteIndex !== null) {
                clientsArray.splice(deleteIndex, 1);
                localStorage.Clients = JSON.stringify(clientsArray);
            }
    
            // Hide the notification and reset deleteIndex
            notificationParent.classList.remove("active");
            deleteIndex = null;
            showClientsData();
        });
    });
    
    function deleteClient(i) {
        deleteIndex = i; // Update the index to be deleted
    
        // Show the notification
        notificationParent.classList.add("active");
    }
    
    

    I think this should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search