0

I am setting some objects on Firebase-database, and showing them on a HTML table with 'child_added' to dynamically add them as soon as they are added to the database, and there has to be a delete button on each row of the table, but I do not know how to make a working button to delete the corresponding database object.

I am dynamically making a table with information coming from a Firebase. database. I want a delete button on each row of my table which deletes the corresponding table from the database.

function vislag(snapshot) {
        let nylag = snapshot.val();
        let idrettRef = database.ref("idrett/" + nylag.Idrett);
        idrettRef.once("value", function(snapshotIdrett) {
            let idrettinfo = snapshotIdrett.val();
            txtTabell.innerHTML += `
            <tr>
              <td>${nylag.navn}</td><td>${nylag.klasse}</td>
              <td>${nylag.antall}</td><td>${idrettinfo.navn}</td>
              <td>
<input type="button" value="delete ${nylag.navn}" onclick="deletelag()"></td>
          </tr>`;
        });
    }

    lag.orderByChild("Idrett").on("child_added", vislag);


function deletelag() {
        databaseobjekt.remove()
    }

I want the onclick function: deletelag() to delete the object from the Firebase database. How do I do that?

1 Answer 1

1

To delete a node from the database, you need to have a DatabaseReference pointing to that specific node, and then call the remove() method on it.

For the code you shared that seems to be:

database.ref("idrett/" + nylag.Idrett).remove();

If you have a list of children, and you want the user to be able to remove any of them individually, you'll typically have to add the ID of each individual child into your HTML. That way you can read the ID of the item that the user clicks on, and delete that specific node.

A simple example of that could be something like:

database.ref('listitems').once('value', (snapshot) => {
  snapshot.forEach((child) => {
    let id = child.id;
    let name = child.val()
    let liElm = `<li id='${id}'>${name}</li>`;
    listElm.appendChild(liElm);
  })
})

And now when somebody clicks on the li, you can delete the correct child node with:

function onLiClick(e) {
  let id = e.target.id;
  database.ref('listitems').child(id).remove();
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.