Currently, I am facing a challenge with my code. I am unsure how to implement the functionality to delete a row when clicking on the X button and retrieve the unique ID of that particular row to append it to the URL. Unfortunately, finding the correct method to extract this ID has proven to be a roadblock for me.
const tBody = document.getElementById("tbody");
var url = "http://localhost:3000/users";
//
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {document.addEventListener('DOMContentLoaded', (event) => {
tBody.innerHTML="";
for(let i = 0; i < data.length; i++){
let newRow = document.createElement("tr");
newRow.innerHTML = `
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].author}</td>
<td> <button class="delete btn btn-primary">X</button> </td>`
tBody.appendChild(newRow);
}
});
});
//
const submitButton = document.getElementById("submit-button");
const titleInput = document.getElementById("inputTitle");
const authorInput = document.getElementById("inputAuthor");
submitButton.addEventListener("click", function(e){
e.preventDefault();
var newUser = {
title: titleInput.value,
author: authorInput.value,
};
var van = true;
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
if (data[i].title===titleInput.value || data[i].author===authorInput.value) {
var z = i + 1;
var x = "/" + z;
var postUrl = url + x;
fetch(postUrl, {
method: 'PUT',
body: JSON.stringify(
{
title: titleInput.value,
author: authorInput.value,
id: data[i].id
}
),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
van = false;
}
}
if(van===true) {
fetch(url, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(newUser)
}).then(response => response.json)
.then(json => console.log(json));
}
});
});
I attempted the following:
var tomb = [];
const removeTomb=(id)=>{
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
var b = {
id: data[i].id,
title: data[i].title,
author: data[i].author
}
tomb.push(b);
console.log(tomb);
}
let index=tomb.findIndex(tomb => tomb.id==id);
tomb.splice(index,1);
console.log(tomb);
});
};
Furthermore, I added
onclick="removeTomb(${tomb[i].id})"
before the X button, but unfortunately encountered an error since removeTomb is undefined.
Could you please clarify the functionality of this process? I am eager to learn more! Thank you kindly!