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

Javascript does not have the capability to parse JSON

Received a JSON response from a PHP file: [ { "color": "black", "product_name": "Prod2", "revision": "apps/" }, { "color": "green", "product_name": "Prod1", "revision": "dev/" } ] (successfu ...

Whenever I use jQuery to dynamically add a new form input, the Select2 input fails to function properly

For my form, I'm attempting to dynamically add a new form-row each time the user clicks the add button. <div class="form-row mb-2"> <div class="form-group col-md-3 my-2"> <label>File</label> ...

What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma. There is an array containing data var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];. The goal is to pair the elements and generate a new array of arrays such as var newArray = [[1 ...

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

What is the best way to transfer values dynamically with C# code in jQuery?

Can anyone guide me on passing values dynamically in C# code using jQuery? I am currently working on a timepicker control application using jQuery in Visual Studio.NET. I have successfully passed values statically, but I'm unsure how to do it dynamic ...

Is it possible for me to replicate this full-screen flash animation using jQuery?

I need some guidance on how to create an animation similar to the one on http://flatuicolors.com without using flash. When you click a color on the website, it triggers a full screen animation with text. I'm not asking for code, just ideas on how to ...

Issue: Angular JS radio input not functioning as expected

Below is the code snippet in question: <div ng-controller="TestController"> <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input> </div> <script type="text/javascript"> ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Struggling with my jQuery Ajax call, need some help

I am attempting to create an ajax request that will update the content of my select element. Below is the code for my request : $(function() { $("#client").change(function() { type: 'GET', url: "jsonContacts. ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Tips for Preserving the HTML Page State After Making jQuery Changes

Hi there! I am currently working on developing a card game using HTML5, CSS3, and Javascript. This game will communicate with a server built on node.js, facilitated by socket.io for data transmission. One of the key features I am trying to implement is th ...

What is the best way to remove an object element by index within AngularJS?

One of my challenges involves dealing with objects, specifically $scope.formData = {} I am trying to figure out how to remove an element from the object using the index $index: $scope.formData.university[$index]; My attempt was: $scope.formData.univer ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

Animate a nested element dynamically with jQuery

Whenever I click on the "view" button, I am dynamically adding data to a div. This feature is working perfectly fine. However, I wanted to improve it by adding another nested dynamic element. The problem I'm facing now is that when I try to expand al ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...