Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they choose to do so.

var pageTitle = document.getElementById("titulo");

pageTitle.addEventListener("click", function() {
  pageTitle.textContent = "Welcome to your agenda";
});


var addButton = document.getElementById("adicionar-contato");

addButton.addEventListener("click", addContact);

function addContact(event) {
  event.preventDefault();




  var contactTr = document.createElement("tr");

  var contactForm = document.getElementById("formulario");


  var nameTd = document.createElement("td");
  var emailTd = document.createElement("td");
  var phoneTd = document.createElement("td");
  var instaTd = document.createElement("td");
  var fbTd = document.createElement("td");
  var deleteTd = document.createElement("td");


  nameTd.textContent = contactForm.name.value;

  emailTd.textContent = contactForm.email.value;
  phoneTd.textContent = contactForm.phone.value;
  instaTd.textContent = contactForm.insta.value;
  fbTd.textContent = contactForm.fb.value;
  deleteTd.innerHTML = "<button class='btn btn-danger excluir'><i class='fa fa-trash-o' >Delete</i></button>";

  contactTr.appendChild(nameTd);
  contactTr.appendChild(emailTd);
  contactTr.appendChild(phoneTd);
  contactTr.appendChild(instaTd);
  contactTr.appendChild(fbTd);
  contactTr.appendChild(deleteTd);



  var agendaTable = document.getElementById("corpoAgenda");
  agendaTable.appendChild(contactTr);
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script>


<div class="p-5 text-black text-center bg-roxo">
  <h1 id="titulo">John Doe</h1>
</div>

<div class="container mt-5">
  <div class="container">

    <h5>Agenda</h5>
    <form id="formulario">
      <div class="row py-2">
        <div class="col-1">
          <label for="name">Name:</label>
        </div>
        <div class="col-5 ">
          <input type="text" class="form-control" placeholder="Enter first name" name="name">
        </div>
      </div>

      <div class="row py-2">
        <div class="col-1">
          <label for="email">Email:</label>
        </div>
        <div class="col-5">
          <input type="text" class="form-control" placeholder="email" name="email">
        </div>
        <div class="col-1">
          <label for="phone">Phone:</label>
        </div>
        <div class="col-5">
          <input type="text" class="form-control" placeholder="(XX)XXXX-XXXX" name="phone">
        </div>
      </div>

      <div class="row py-2">
        <div class="col-1">
          <label for="insta">Instagram:</label>
        </div>
        <div class="col">
          <input type="text" class="form-control" placeholder="Instagram" name="insta">
        </div>
        <div class="col-1">
          <label for="fb">Facebook:</label>
        </div>
        <div class="col">
          <input type="text" class="form-control" placeholder="Facebook" name="fb">
        </div>
      </div>


      <div class="salvarexcluir">
        <button type="button" class="btn btn-info" id="adicionar-contato">Save</button>


        <button class='btn btn-danger exluir'><i class='fa fa-trash-o'>Delete</i></button>

      </div>



    </form>

  </div>


  <div class="container mt-3">
    <table class="table table-striped" id="myTable">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Instagram</th>
          <th>Facebook</th>
          <th>Delete</th>
        </tr>

        <tr>

      </thead>
      <tbody id="corpoAgenda">

      </tbody>
    </table>
  </div>

</div>

<div class="mt-5 p-4 bg-dark text-white text-center">

</div>

Answer №1

Instead of implementing a global "delete" action for the table, you should assign the click event individually to each delete button in every row. This way, you can accurately reference and delete the desired row.

The crucial modification here is adding the following lines to your row creation function:

// attach the "delete" action to this button for this row
excluirTd.querySelector('button').addEventListener("click", () => {
  deletar(contatoTr)
})

Your previous code attempted to pass a reference to the button to the deletar function and then traverse back to its parent node to find the corresponding row and its rowIndex. However, this approach failed because the button's parent node was actually the <td> element instead of the desired <tr>. Although you could fix this by using parentNode.parentNode, it would be quite fragile. In my solution, I have streamlined the process by simply passing the row itself, as you already have a convenient reference to it in contatoTr.

See the demonstration below (with extraneous code and layout removed):

function deletar(tr) {
  var tabela = document.getElementById('myTable');
  tabela.deleteRow(tr.rowIndex);
}

var botaoAdd = document.getElementById("adicionar-contato");

botaoAdd.addEventListener("click", addContato);

function addContato(event) {
  event.preventDefault();

  //Creating a tr
  var contatoTr = document.createElement("tr");

  var formContato = document.getElementById("formulario");

  //Creating 06 tds
  var nomeTd = document.createElement("td");
  ...
  
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5855554e494e485b4a7a0f14081409">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container">
  <form id="formulario">
    <div class="row py-2">
      <div class="col-1">
        <label for="nome">Name:</label>
      </div>
      ...

</div>

//Table to contain the data
<div class="container mt-3">
  <table class="table table-striped" id="myTable">
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Instagram</th>
        <th>Facebook</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody id="corpoAgenda">
    </tbody>
  </table>
</div>

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

Is there a way for me to make this Select update when onChange occurs?

I am facing an issue with a react-select input that is supposed to display country options from a JSON file and submit the selected value. Currently, when a selection is made, the field does not populate with the selection visually, but it still sends the ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

Discover the art of customizing child elements using vanilla extract!

I recently started using vanilla extract to add styles to a NextJS application. Is there a way to style child elements within the parent element without having to create another class? My React component has a structure like this: <ul className={style ...

What could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

After refreshing, a blank page appears when using the HTML POST method

After conducting a test using an HTML form with the POST method, I encountered an unexpected outcome. The setup involved two HTML pages hosted on an Apache server (with PHP already installed): post.html and target.html. Below are the code snippets for thes ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

Controlling the page scroll when adding data using jQuery

I am encountering an issue with a webpage that displays around 20 pictures in separate divs stacked vertically. Below these 20 pictures, there is a "show more" button that, when clicked, loads another set of 20 pictures and appends them to the existing dat ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

What is the best way to save the output of a middleware in express js so that it can be conveniently accessed by the rest of the

Currently, I am working with a middleware that returns an object. My goal is to save this object so that other parts of the application can utilize the data it contains. How can I achieve this? This snippet is from my app.js file: import { myMiddlewareFun ...

Is there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

Stop all animations in JS and CSS

Looking for a way to halt all CSS and JavaScript animations, including canvas and webGL effects, on a specific webpage. Some animations can cause slow performance on certain browsers like Opera and Firefox, so I'm seeking a code snippet or guidance o ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Is it possible to use TypeScript in a React Native project with a JavaScript file?

Currently, I am learning React Native by working on app clones like Instagram and YouTube. I have recently started an AirBnb clone project, but I'm facing some issues with the initial build. One issue I noticed is that in 'App.js', the temp ...

The mouse scurries away once the div height has been adjusted

How can I make the height of #header change when hovering over #hoverme, and then revert back to its original height when the mouse leaves #hoverme? If anyone knows a solution, please check out my jsfiddle as it's not working as I intended. Here is ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

The FontLoader feature seems to be causing issues when integrated with Vuejs

While working on a Vue project with threejs, I encountered an error similar to the one described here. The issue arose when attempting to generate a text geometry despite confirming that the path to the typeface font is accurate and in json format. ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...