Attempting to eliminate a specific row within a table using HTML and JavaScript

Programming with JavaScript

function removeElement(el) {
el.parentElement.remove();
}

document.getElementById('myButton').onclick = function () {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
const nameTd = '<td>' + name + '</td>';
const dateTd = '<td>' + date + '</td>';
const amountTd = '<td>' + '$'+ amount + '</td>' + '<td>' + 
'<button id="removeBtn"type="button" onClick="removeElement(this)">X</button></td>';
const tr = '<tr>' + nameTd + dateTd +  amountTd + '</tr>';
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
document.getElementById('clearList').onclick = function () {
    const cl = document.getElementById('table');
    while (cl.hasChildNodes()) {
        cl.removeChild(cl.firstChild);
    }
}
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
}    

Building the Front-End Interface with HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<h3>Add A New Item:</h3>
<label>Name: <input text="text" id="name"></label><br>
<label>Date:<input type="date" id="date"></label><br>
<label>Amount:<input text="text" id="amount"></label><br>
<button type="button" id="myButton">Add Expense</button>
<button type="button" id="clearList">Clear List</button>
<br>
<br>
<br>
<br>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Date</th>
        <th>Amount</th>
        <th>Remove</th>
    </tr>
    <tbody  id="table">

    </tbody>
</table>


<script src="script2.js"></script>
</body>
</html>

Hello there! I'm currently working on a feature where users can remove an expense item by clicking the "X" button. However, I encountered an issue where clicking the button only removes the button itself and not the entire input field. Can you help me troubleshoot this problem?

Answer №1

When you need to remove the parent element that contains a button, remember that it is likely a td element. To actually remove the grandparent, use this code snippet:

el.parentElement.parentElement.remove();

If you prefer a simpler approach, consider targeting the closest tr element among the ancestors:

el.closest("tr").remove();

function takeOut(el) {
  el.closest("tr").remove();
}

document.getElementById('myButton').onclick = function() {
  const name = document.getElementById('name').value;
  const date = document.getElementById('date').value;
  const amount = document.getElementById('amount').value;
  const nameTd = '<td>' + name + '</td>';
  const dateTd = '<td>' + date + '</td>';
  const amountTd = '<td>' + '$' + amount + '</td>' + '<td>' +
    '<button id="removeBtn"type="button" onClick="takeOut(this)">X</button></td>';
  const tr = '<tr>' + nameTd + dateTd + amountTd + '</tr>';
  document.getElementById('table').insertAdjacentHTML('beforeend', tr);
  document.getElementById('clearList').onclick = function() {
    const cl = document.getElementById('table');
    while (cl.hasChildNodes()) {
      cl.removeChild(cl.firstChild);
    }
  }
  document.getElementById('name').value = '';
  document.getElementById('amount').value = '';
  document.getElementById('date').value = '';
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Expense Tracker</title>
</head>

<body>
  <h1>Expense Tracker</h1>
  <h3>Add A New Item:</h3>
  <label>Name: <input text="text" id="name"></label><br>
  <label>Date:<input type="date" id="date"></label><br>
  <label>Amount:<input text="text" id="amount"></label><br>
  <button type="button" id="myButton>Add Expense</button>
  <button type="button" id="clearList>Clear List</button>
  <br>
  <br>
  <br>
  <br>
  <br>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Date</th>
      <th>Amount</th>
      <th>Remove</th>
    </tr>
    <tbody id="table">

    </tbody>
  </table>


  <script src="script2.js"></script>
</body>

</html>

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

Using Vue.js for instant field validation when sending PHP post forms for enhanced user experience

A unique approach is being taken to utilize vue.js exclusively for real-time field validation, while the form will ultimately be submitted using PHP through the POST method. However, a challenge arises where vue.js takes control of the form, hindering PHP& ...

Learn the process of choosing and displaying all articles belonging to the logged-in user with JavaScript and MongoDB!

Using the code snippet below, I am able to retrieve all articles: getAllPost: (req, res) => { Article.find({}).limit().populate('author').then(articles => { res.render('home/AllPost',{ articles ...

What are the advantages of using the CRUD coding style with Redux?

Seeking guidance on the best coding style for a single page application regarding the use of React Redux For instance, consider a standard CRUD page where data is presented in a table with a pop-up modal form. The table's data comes from server-side ...

CoffeeScript is failing to run the code

I'm attempting to use a click function to alter the CSS code and then run a function. Here is my current code: ready: -> $("#titleDD").click -> $("#titleDD").css('text-decoration', 'underline'); $("#catDD").css( ...

Sending optional data in Angular routesIn Angular, you can include additional

In my project utilizing angular 5, I have a lengthy routing file: const homeRoutes: Routes = [ { path: 'home', component: HomeComponent, children: [ { path: 'registration', component: RegistrationCompone ...

Learn how to run javascript code using Nodejs child_process and Meteor

Is it possible to use the child_process module to execute Meteor server-side code instead of just Linux commands? I am interested in using spawn to create a separate process for running my loop. The loop involves logging a message every minute. myLoop(){ ...

Creating a Loop with JavaScript through a List

My current API response format is: "imagePath": "path1", Here is the JavaScript code I am using: <div className="flexAlignCenterJustifyCenter"> {event.imagePath ? ( <img src={event.imagePath} onErro ...

"Embrace the power of Bootstrap 3 with a cutting-edge logo,

Looking to design a layout that features a logo on the left and a slogan pane with the navigation bar below it on the right. Check out image #1 for reference. As the screen narrows, the plan is to have the navigation pane move below the logo and slogan. T ...

instructions for transferring image filenames to a database with the help of multer and express

While utilizing multer and express to upload a photo, everything appears to be functioning correctly. However, I am encountering issues with sending the image name to the mongoose database. The images are successfully uploaded to the upload directory. Alt ...

Using multiple GET methods on a single route in Express and Sequelize can lead to conflicts

I've created a simple product CRUD application with routes to search for products by ID and by name. However, when I send a request to http://localhost:4000/products?name=pen, the routes conflict with each other and I'm unable to retrieve the pro ...

Design a clickable div element embedded within an interactive article using HTML5

Currently, I am facing an issue with placing clickable div elements inside an article tag in HTML5. The problem is that when I try to click the divs, it registers as a click on the article itself. Below is an example of my code: HTML: <article id=&apo ...

Is it possible to use AJAX to change the class name of a Font Awesome icon?

I am considering updating the icon after deleting a row. Should I initially include the font awesome icon once in the blade, then remove the class name and add it back with ajax? blade: <div id="status-{{ $country->id }}"> <div id ...

Identify and emphasize unfilled inputs in a form using Bootstrap

I am working on an "Update Profile" form and I want to draw attention to empty input fields that are not required but would be beneficial for users to fill in. Is there a way to highlight these empty fields, perhaps with a glowing effect or some other form ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

What is the best way to position a span overlay on a card in the lower right corner

I am looking to add a thumbnail with the duration displayed in the bottom right corner of a video, but I am facing issues moving the span object within the card using Bootstrap 4. Whenever I try to increase the margin-left beyond 50%, the span object crash ...

Enable automatic indentation for wrapped text

I'm still learning the ropes here, but I'm looking to have text automatically indent when it's wrapped. Instead of this: Peter piper picked a peck of pickled peppers. It should look like this: Peter piper picked a peck of pickled pepp ...

The form does not support inserting all values through AJAX. We may need to implement a QUERY to handle this

Can someone help me find the issue in my code? I have checked the back end and can't seem to identify the logic error. The form submission shows as successful but does not insert the values into the database. I'm still learning how to use ajax, s ...

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

Having trouble receiving time increments while utilizing the datetimepicker

I am using a datetime picker with jQuery and I would like to only select the time without the date. When I click on the input, I am only able to pick hours. How can I fix this? $(document).ready(function() { $.datetimepicker.setDateFormatter(&a ...