Kaido Bagua
Kaido Bagua

Reputation: 35

How can I do multiple delete in js?

I want to have a confirmation before deleting an account. How can I do it?

This is the picture for the UI of the accounts. enter image description here

This is the html code.

<a href="uses_script.php?user_id=<?php echo $row['id'];?>&username=<?php echo $_SESSION['user_username']; ?>" 
                      id = "del"
                      data-toggle="tooltip" 
                      data-placement="top" 
                      title="Delete"> 
                      <i class="mdi mdi-close"></i></a> 

This is the javascript.

const deleteIcon = document.querySelectorAll("del");
deleteIcon.addEventListener("click", (e) => {
  const confirmVar = confirm("Do you want to proceed? ");
  if (!confirmVar) e.preventDefault();
}

What I want to do is before deleting users I want to have a confirmation that when I click OK it will delete and when I click cancel it will just close.

Upvotes: 1

Views: 241

Answers (2)

Mr. Programmer
Mr. Programmer

Reputation: 95

This might be the correct code.

const deleteIcon = document.querySelectorAll("#del");
deleteIcon.forEach ((element) => {
  element.addEventListener("click", (e)=>{  
  const confirmVar = confirm("Do you want to proceed?");
  if (!confirmVar){ e.preventDefault();}})
})

I have iterated through the buttons to add the event listener for each of them and I have also added the e parameter so that it identifies the event.

NOTE: addEventListener doesn't work for a collection of elements. You will have to iterate through each element.

Upvotes: 2

LW001
LW001

Reputation: 2893

Your listener is not applied to the element correctly.

Use a # in your Query Selector to target an element by ID:

const deleteIcon = document.querySelector("#del");

However, as there are multiple lines it might not be the best idea to use an ID for the delete button, use a class instead.

Add class="del" (or a class name of your choosing) to your <a> element and use the following Query Selector (using a . means selecting a class):

const deleteIcons = document.querySelectorAll(".del");

This will return a list of elements you can later iterate over to add event listeners to it:

deleteIcons.forEach(function(element) {
    element.addEventListener("click", (e) => {
        const confirmVar = confirm("Do you want to proceed? ");
        if (!confirmVar) e.preventDefault();
    });
});

Further reading:

Upvotes: 0

Related Questions