JavaScript Inserting a new row into a table right above the last row of the table

Here is the code snippet for my table:

Check out my JSfiddle for a live demo.

function insert_Row() {
  var xTable = document.getElementById('partsTable');
  var tr = document.createElement('tr');
  tr.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>";
  xTable.insertBefore(tr, xTable.lastElementChild.previousElementSibling);
}
<table class="table table-bordered table-striped" id="partsTable">
  <thead>
    <tr class="bg-primary">
      <th colspan=2>Services</th>
      <th>Amount</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control'> </td>
      <td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control'></td>
    </tr>
    <tr>
      <td colspan=3><button onclick="insert_Row();">+</button></td>

    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class="col-md-6"> &nbsp </td>
      <td><strong>Total</strong></td>
      <td><strong>$1000.00</strong></td>
    </tr>
  </tfoot>
</table>

I encountered an issue where the new tr is being added at the end of the tbody. I'm looking for a solution to insert the new tr one place before the last tr. Is there a way to achieve this?

Answer №1

If you need to add a row to a table at a specific position, there is a convenient method available just for that:

function addNewRow()
{
    var table = document.getElementById('partsTable');
    var index = table.rows.length - 1;
    var newRow = table.insertRow(index);
    newRow.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>" ;
}

Answer №2

If you need to locate the specific row where you want to insert a new one, you can utilize the insertAdjacentHTML method with either the beforebegin option to insert before or beforeend to append.

function addNewRow(button)
{
    var table=document.getElementById('partsTable');
    var body = table.tBodies[0];
    var rows = body.rows;
    
    // Select the last row and prepend a new one
    rows[rows.length - 1].insertAdjacentHTML('beforebegin', "<tr><td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td></tr>");
}
<table class="table table-bordered table-striped" id="partsTable">
    <thead>
        <tr class="bg-primary" >
            <th colspan=2>Services</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control' > </td>
            <td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control' ></td>
        </tr>
        <tr>
            <td colspan=3><button onclick="addNewRow();">+</button></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td class="col-md-6"> &nbsp </td>
            <td><strong>Total</strong></td>
            <td><strong>$1000.00</strong></td>
        </tr>
    </tfoot>
</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

Switch the toggle to activate or deactivate links

My attempt at coding a switch to disable and enable links using CSS is functional in terms of JavaScript, but the appearance is not changing. I am lacking experience in this area. Here is my HTML Button code: <label class="switch" isValue="0"> ...

What is the best way to incorporate options using jQuery?

Currently, I am incorporating a jQuery plugin for modals into my website. The plugin/code offers the functionality to customize the background color of the modal. For more details on how to do this, you can visit the plugin's official website. Althou ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Sorting a 2D array in Javascript based on numerical values

I've come across a few similar posts regarding this issue, but none have provided solutions that work for my specific situation. I'm feeling lost on how to solve this problem (like Sort a 2D array by the second value) Let me explain the challeng ...

Issues with jQuery Progress Bar Functionality

As a beginner in jQuery, I am currently working on creating an interactive progress bar using jQuery. My goal is to provide a set of checkboxes on a webpage so that when a visitor checks or unchecks a checkbox, the value displayed on the progress bar will ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Preventing touchstart default behavior in JavaScript on iOS without disrupting scrolling functionality

Currently experimenting with JavaScript and jQuery within a UIWebView on iOS. I've implemented some javascript event handlers to detect a touch-and-hold action in order to display a message when an image is tapped for a certain duration: $(document) ...

When transferring information from the UI controller to Javascript, there is a risk of losing certain data points in the process

My UI controller is returning data with two objects of the same type, each representing a certain entity. Both objects have values assigned to them, as shown when fully expanded. https://i.sstatic.net/Txhwh.png However, when inspecting the JavaScript, th ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Navigating through pages using Nuxt UI-pagination

Having some trouble with setting up the pagination feature from Nuxt UI. Despite trying to research through documentation and videos, I can't seem to figure out how to connect my data to the component. <template> <div> ...

Retrieving PHP data with jQuery

Isn't it interesting that I couldn't find anything on Google, but I believe you can assist me. I have a Table containing different accounts. Upon clicking on a specific row, I want another table related to that account to slide in. This secondary ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Is there a way to modify the space bar and enter key functionality exclusively for the third button, rather than applying it to all buttons?

https://jsfiddle.net/ffkwgddL/ In the code, I have three buttons named first-button, second-button, and third-button. If the first-button (introduction) is clicked and then the space bar is pressed, it functions as if the first button was clicked again. H ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

Numpad functionality in JQuery malfunctioning post-ajax request

Using the jQuery numpad plugin has been flawless until after an AJAX call. I have tried various functions like on('click') and others, but unfortunately, none of them worked as expected. Apologies for my poor English! You can find the extension l ...

What is the best way to sum the numbers in this code snippet?

I'm trying to iterate through an array called arr = [[1,2],4] using for loops to access the numbers. However, I've noticed that I can't seem to add the last number for some reason. Can anyone explain why this is happening? let arr = [[1, ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...