Is there a way to remove data from both a JSON file and an HTML document?

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!

Answer №1

When using the const keyword, the function literal approach may not work properly with the HTML element

onclick="removeTomb(${tomb[i].id})"
. Instead, try assigning the function to the window object as shown below:

window.removeTomb = removeTomb

OR

var tomb = [];
function 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);
     });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

Click on the text within a paragraph element

Is there a way to retrieve the selected text or its position within a paragraph (<p>)? I'm displaying a text sentence by sentence using a Vue.js loop of paragraphs. <p class="mreadonly text-left mark-context" v-for="line in ...

Tips for having <script> update onchange instead of just onload

Is there a way to update the output of the <table id="mortgagetable"> each time a user changes the input values in the form? Currently, it only updates on load. Additionally, the content of the <div id="years" style="display:inline-block;">25 ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Create an input element using JavaScript/jQuery

Looking for some help with Javascript on a simple task. When a specific option is chosen, I want to add an input field to a div element. <select name="amount" > <option value="50">50$</option> <option value="100">100$</o ...

Exploring the contents of Google's response JSON documents

Hey everyone, I'm new to all of this so please bear with me if this seems like common knowledge to some of you. I've been using the request package for Node.js to send an HTTP request to the Google places API. The API responded with a JSON file ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

The React Native File generator

Currently, we are utilizing redux actions in our web project. In an effort to share logic between web and native applications, we have integrated these actions into our react native project with the intention of only having to modify the components. One o ...

Is there a library available for generating QR codes on the server side and saving them directly to a database

My Goal: I am looking to create a functionality where, upon clicking "Generate QRCode," JavaScript will utilize the local machine's datetime to generate an md5 hash in the MMDDYYHHMMSS format. I then want this hash to be sent to the server to produce ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

Exploring the topic of AngularJS unit testing and working with httpBackend timeouts

I have experience in the testing world, particularly with TDD using tools like mocha, sinon, chai, and nodejs. Recently, I've been finding AngularJS testing a bit challenging to grasp and implement. Currently, I am trying to test the simplest method ...

Webpage Text Animation

This is the visual representation of my webpage: https://i.stack.imgur.com/tYq34.png I am seeking to implement a uniform animation effect for the text "Carlos Qiano" and "Lorem Ipsum", similar to the link below: https://i.stack.imgur.com/XVnBS.jpg Note: ...

What is the best way to display the data model in Angular as HTML?

I am facing an issue with my data-model where it needs to be converted or displayed as HTML, but currently it is only appearing as plain text. Here is the HTML code snippet: <div ng-repeat="item in ornamentFigures" class="ornament-item"> <la ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

Unreliable Response from JEditable

I have encountered an unusual behavior while using the JEditable jQuery plugin to update data on my webpage. One specific field is not updating as expected, instead displaying the following message: EM29UPDATE NetLog SET grid = 'EM29&apo ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

What is the best way to guide a user to a specific page based on the choice they made after submitting a form?

My form includes a list of 6 options where users can only select one. After submitting the form, I want to redirect them to a specific page based on their selection. For example, I have the following 3 options: Facebook Youtube Twitter If a user selects ...