JavaScript - Insert rows within the tbody element by adding them after the opening tbody tag. The new rows should be

Having trouble adding rows in JavaScript. The code is functioning correctly, but the new rows are appearing after the tbody tag instead of inside it.

Here's a snippet of the code:

function deleteRow(row) {
  var i = row.parentNode.parentNode.rowIndex;
  document.getElementById('add-row').deleteRow(i);
}

function insRow() {
  var x = document.getElementById('add-row');
  var new_row = x.rows[1].cloneNode(true);
  var len = x.rows.length;
  new_row.cells[0].innerHTML = len;

  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
  inp1.id += len;
  inp1.value = '';
  x.appendChild(new_row);
}
<table class="table  table-hover" id="add-row">
  <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th style="text-align:right;">Delete</th>
    </tr>
  </thead>
  <tbody id="add-row1">
    <tr>
      <td>1</td>
      <td>
        <input type="text" class="form-control input-sm" placeholder="Enter Group Name" id="group" />
      </td>
      <td class="pull-right">
        <button class="btn btn-sm btn-danger" id="delPOIbutton" onclick="deleteRow(this)"><i class="fa fa-close"></i> Delete</button>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">
        <button class="btn btn-sm btn-success pull-right"><i class="fa fa-save"></i> Save</button>
        <button class="btn btn-sm btn-primary" id="addmorePOIbutton" onclick="insRow()"> <i class="fa fa-plus"></i> Add</button>
      </td>
    </tr>
  </tfoot>
</table>

Answer №1

Instead of using the table id, you can utilize the id of tbody for the appendChild operation. The id of the table should be used to create the row, while tbody is used to append the child element.

Check out the Live Demo here

function insRow() {
    var x = document.getElementById('add-row');
    var x1 = document.getElementById('add-row1');
    var new_row = x.rows[1].cloneNode(true);
    var len = x.rows.length;
    new_row.cells[0].innerHTML = len;

    var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
    inp1.id += len;
    inp1.value = '';
    x1.appendChild(new_row);
}

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

Guide on separating a Chart.js chart with reactive attributes into its own component in Svelte

After creating a Skeleton Project using the command npm create svelte@latest myapp, I proceeded to install Chart.js with npm install svelte-chartjs chart.js and then created a basic bar chart: <script> import { Bar } from 'svelte-chartjs' ...

Navigating Modal Pop-ups in Django

My current approach for handling modal windows involves referring to this article here. However, I am struggling with implementing some basic functionality using this method. Within my HTML code, I have the following structure: {% for order in queryset% ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

The process of retrieving matching strings from two collections in MongoDB

There are two collections: Collection A consists of: -> {"_id": .... , "data":"demon"} -> {"_id": .... , "data":"god"} and Collection B consists of: -> {"_id": .... , "tit ...

What does the JS Array Filter function return?

Is it necessary to include a return statement in the filter function when NOT using ES6 arrow syntax? Could the two separate filter functions be combined into one for efficiency? cars.filter(function(car, index) { return car[0].setAttribute("data-ori ...

Transfer data from TWO input fields within a PHP document to another PHP document using only one submission button

Is it possible to have two textboxes and submit the values entered in them to another PHP file using a single submit button? Transferring value from page1.php to page2.php Currently, I am able to pass a value from one text box: <form action='pag ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Decreasing the gap between two <tr> elements

Looking to showcase a company logo alongside the company name without using flexbox for compatibility with older browsers? Take a look at this simple HTML and CSS code snippet: <table style="background-color: cadetblue;width:100%;padding:10px"> ...

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

Verification of unique custom string

How can I ensure that a string follows the specific format of x.xx.xxxxx? The first character is mandatory, followed by a period, then two characters, another period, and finally any number of characters of varying lengths. ...

How to enable seeking functionality for mp3 files with PHP

I have implemented the following PHP script: video tags are unable to extract metadata from it. Any insights on where I might be going wrong and how to rectify this situation? Your guidance would be greatly appreciated. Thank you.</p> ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

Tips for Deactivating a Button Following a Single Click

I am currently developing a react-native app and I'm in need of assistance with my code stack. My requirement is to disable a button after it has been clicked once. Can anyone provide guidance on this issue? The challenge I am facing is that I cannot ...

hidden behind the frame is a drop-down menu

I am currently working on a website that uses frames. The topFrame.php contains a menu with drop-down submenus, while the main frame displays the website content. However, I am encountering an issue where the submenu in the topFrame is getting hidden beh ...

Is it possible to utilize the Wicket:id for generating CSS?

Can the wicket:id attribute of an element or component be used for CSS styling instead of the "class" attribute? For example: .tooltipster-arrow span, .column-shifter { display: block; width: 0; height: 0; position: absolute; } Let&apos ...

Having trouble with your browser freezing up after an AJAX request finishes?

Going through a tough time trying to figure this out for the past two days, but still struggling without any clue. Here's what I've been up to: Firstly, I upload a file using AJAX and instantly start processing it on the backend. $.ajax({ t ...

Notification continuously appears when clicking outside of Chrome

I have implemented the use of onblur on a text box to display an alert. However, I encountered an issue where if I click outside my Chrome browser after entering text in the text box and then click on the Chrome browser button in the task bar, the alert ap ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...