Issue encountered while attempting to remove a row from a table (JavaScript)

I'm encountering an error when attempting to delete a table row: "Uncaught ReferenceError: remTable is not defined index.html:1:1". When I inspect index.html to identify the issue, I find this:

remTable(this)

This is my code:

const transactions = {
    addTable(){
        sModal.classList.remove();

        let table = document.getElementById("data-table");
        let len = table.rows.length;
        let input = document.querySelectorAll("form input");

        //inserting new row
        let line = table.insertRow(len);
        
        //inserting cells
        let info = new Array(5);
        info[0] = line.insertCell(0);
        info[1] = line.insertCell(1);
        info[2] = line.insertCell(2);
        info[3] = line.insertCell(3);
        info[4] = line.insertCell(4);

        // n
        info[0].innerHTML = len;
        info[1].innerHTML = input[0].value;
        info[2].innerHTML = input[1].value;
        info[3].innerHTML = input[2].value;
        info[4].innerHTML = `
            <img src="assets/minus.svg" onclick="remTable(this)">
        `;
    },
    remTable(r){
        var i = r.parentNode.parentNode.rowIndex;
        document.getElementById("data-table").deleteRow(i);
    }
};

    <tr>
        <th>Example</th>
        <th>Example</th>
        <th>Example</th>
        <th>Example</th>
        <th>
            <img src="assets/minus.svg" onclick="remTable(this)">
        </th>
   </tr>

Answer №1

It seems like there may be some important details missing here, especially since sModal is referenced without being defined anywhere. Assuming there is more code provided elsewhere that functions correctly:

The remTable function appears to be a method of the transactions object based on the current structure. If this is your intention, you will need to invoke remTable as shown below:

onclick="transactions.remTable(this)"

This assumes that the element with the id='data-table' actually exists in your HTML document. To ensure this, it's necessary to first call transactions.addTable(), but this step might not work as expected due to the absence of sModal.

Answer №2

It seems like the code provided is too concise for others to pinpoint where the issue lies.

If this example can guide you, this is how I approach it:

const myForm    = document.forms['my-form']
const tableBody = document.querySelector('table#data-table tbody')

myForm.onsubmit = e =>
  {
  e.preventDefault()
  let len  = tableBody.rows.length
    , line = tableBody.insertRow()
    ;
  line.insertCell().textContent = len
  line.insertCell().textContent = myForm.inoX1.value
  line.insertCell().textContent = myForm.inoX2.value
  line.insertCell().textContent = myForm.inoX3.value
  line.insertCell().innerHTML = `<img class="removLine" src="assets/minus.svg">`

  myForm.reset()        
  }

tableBody.onclick = ({target}) =>
  {
  if (!target.matches('img.removLine')) return

  let line = target.closest('tr')
  tableBody.deleteRow(line)
  }
table  {
  border-collapse : collapse;
  margin          : 2em 1em;
  }
td,th {
  padding    : .2em .8em;
  border     : 1px solid darkblue;
  text-align : center;
  cursor     : pointer;
  }
<form name="my-form">
  <label> input 1 <input type="text" name="inoX1" required> </label><br>
  <label> input 2 <input type="text" name="inoX2" required> </label><br>
  <label> input 3 <input type="text" name="inoX3" required> </label><br>
  <button type="submit">add</button>
</form>

  <table id="data-table">
    <thead>
      <tr>
        <th>Example</th>
        <th>Example</th>
        <th>Example</th>
        <th>Example</th>
        <th> </th>
      <tr>
    </thead>
    <tbody></tbody>
  <table>

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

Click on the social media icon to access the link

Recently, I created a social media icon list for my website but I'm struggling to figure out how to add clickable links to them. I attempted using the "a" tag, but it's not functioning as expected: <div class="leftside"> <ul class= ...

Transforming three items into an array with multiple dimensions

There are 3 unique objects that hold data regarding SVG icons from FontAwesome. Each object follows the same structure, but the key difference lies in the value of the prefix property. The first object utilizes fab as its prefix, the second uses far, and t ...

Creating multiple versions of a website based on the user's location can be achieved by implementing geotargeting techniques

It may be a bit challenging to convey this idea clearly. I am interested in creating distinct home pages based on the source from which visitors arrive. For instance, if they come from FaceBook, I envision a tailored home page for FaceBook users. If they ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

Advantages and drawbacks of utilizing both of these HTML codes for generating an image

Could you explain the distinction between creating the image in these two code snippets? <link href="img/favicon.ico" rel="icon" type="image/png"> compared to initiating it using a simple <img /> tag I'm t ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

Is there a way to make this AngularJS service wait until it has a value before returning it?

Multiple controllers call a service that loads data into an object named categories: .service('DataService', ['$http', '$q', function($http, $q) { var categories = {}; // Public API. return({ setCategory ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Encountered a 404 error while trying to install body-parser

Hey there, I'm new to this and ran into an issue while trying to install the body-parser package. Can you please guide me on how to resolve this problem? D:\Calculator>npm install body-paeser npm ERR! code E404 npm ERR! 404 Not Found - GET htt ...

Is it possible to generate this result using only Bootstrap 5.2.3?

I'm currently working on a simple HTML project that aims to replicate the layout shown in the image below. I want the output to look exactly like what's displayed in the provided image. The task does not require CSS, only Bootstrap is needed for ...

When an SVG image is embedded, its color may not change even after being converted to an inline SVG

I've inserted an SVG using an img tag. When hovering over it, I want the fill color of the SVG to change. I attempted to convert the SVG to inline SVG following this method, but it doesn't seem to be working as expected. No console errors are b ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

Why isn't my Vue2 data updating in the HTML?

Starting my journey with Vue, I have been finding my way through the documentation and seeking support from the Vue community on Stack Overflow. Slowly but steadily, I am gaining a better understanding of how to create more complex components. The issue I ...

Displaying a mouse cursor using an A-frame function

I am presently working on a scene using A-frame () in which I have hidden the mouse pointer. Is there a way for me to set it up so that when a specific function is triggered, the mouse pointer will show, and when another function is executed, the mouse poi ...

Don't pay attention to CSS that is outside of the div

Currently, I am attempting to populate a div with templates in order to preview them. These templates are sourced from a database and configured using php. My issue lies in the fact that certain entries consist of entire websites (complete with a head and ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

How can the dependencies object be extracted from the package.json file in an Angular project?

Scenario: I am managing multiple Angular applications within the same project. Whenever I need to upgrade an npm package, I find myself having to manually update the package.json files in each application. While I attempted a mono repo approach, it did not ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

Is there a way to align these blocks in a single row?

Having trouble aligning these buttons horizontally. Any suggestions? I've been tinkering with this for a couple of hours now, so decided to seek help here. The desired effect should resemble the image below, but it's not quite there yet. Thank yo ...