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

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Is it possible to retrieve a variable from a geojson file using Vue 3 and Vite?

For my Vue 3 project, I am trying to import a variable from a geojson file. However, when I use import line from '@static/line.geojson', my page goes blank and it seems like Vue stops working. If I use import line from '@static/line.json&ap ...

MUI: The value you have chosen for the select component is outside the acceptable range - `[object Object]`

I'm currently in the process of developing a custom Select component that offers both single and multi-selection features. Below is how I initialize the components: const vendorList = [ { label: "John", value: "668", } ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

What is the best way to customize the source code within node modules dependencies?

Hello everyone! I'm facing a challenge with my project. I'm trying to make changes to the code of a component from a UI library, such as Semantic-UI or Material-UI. Currently, I am directly editing the code within the node_modules folder. However ...

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

What is the correct method for setting a scope variable from a service in Angular?

Is there a way to retrieve the return value from a service method and set it into the scope for further processing in the template? I've discovered that I cannot directly access the scope within services. While I could use Rootscope, I believe there ...

Attempting to utilize Vue js to connect to an API

I'm currently facing difficulties while trying to access an API in order to retrieve data. As a novice in the world of vue.js and javascript, I encountered an error message saying Uncaught SyntaxError: Invalid shorthand property initializer. Unfortuna ...

Support for Arabic in database, PHP, and JavaScript

After inputting an Arabic comment into a textarea on the site, it displays correctly as "عربي" and is successfully sent to the database. However, upon refreshing the page, the text appears garbled: "عربÙ�". I attempted to directly enter s ...

Creating a Slider with a Multitude of Images

I am working on a project to develop a gallery that pulls images from a JSON source. I have successfully implemented infinite scrolling to display the images on the first page. However, I am now facing a challenge when it comes to showing the selected imag ...

Filtering data with React's multiselect checkboxes

I have created an amazing app that fetches a list of todos from this incredible source To enhance user experience, I developed a special CheckBoxDropDown component for selecting todo IDs Within the CheckBoxDropDown.js component, I am passing the onChange ...

"Preventing the propagation of a click event on an anchor tag with

Is there a way to prevent the parent anchor from executing its href when a child element is clicked, despite using stopPropagation? Here is the markup provided: <div id="parent"> <h5>Parent</h5> <a id="childAnchor" href="https:// ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function? const hashPassword = async password => await bcrypt.ha ...

Issue uploading with Candy Machine Version 2/ complications with directory

For some reason, I am encountering issues with the upload operation. Switching from relative to absolute paths did not resolve the error, and using the -c flag for the directory containing images and JSON files is causing a problem. However, other flags ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

Using jquery to toggle the visibility of input fields

I'm encountering an issue with this straightforward code snippet: $("#additional-room").hide(); var numAdd = 0; $("#add-room").click(function(e) { e.preventDefault(); $("#additional-room").show(""); if (numAdd >= 3) return; numAd ...

How can we use PHP and jQuery to open a simple modal with data?

Here is a basic modal setup: <div id="info" style="display: none;"> <h3 class="title">User Information</h3> <table border="0" cellpadding="5" cellspacing="0"> <tr> <td width="50%" align="right ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...