Creating an Additional Table Row Dynamically with JavaScript's AppendChild() Method

Just to provide some background, the Bootstrap CDN is connected in my code, but unfortunately I can't paste it here at the moment.

As I run this script, the initial submission successfully generates a table row with the id='masterTable'. However, upon subsequent submissions, the content just gets appended to the same row instead of creating a new one.

I'm trying to figure out how to make a new table row every time the submit button is clicked, but I seem to be stuck. Any suggestions?

<!DOCTYPE html>
<html>
<link>
</link>
<head>
</head>
<body>
<div class="d-flex">

<div>
<select id="ddlViewBy">
<option value="0310">XXXX-10</option>
<option value="4610" selected="selected">XXXX-10</option>
<option value="4610">XXXX-10</option>
</select>
</div>
</div>
<form>
<div class="form-group">
<label>Hand Trucks</label>
<input type="text" class="form-control" id="handtrucks" placeholder="Enter 
number of Hand Trucks.">
</div>
<div>
  <label>Furniture Pads</label>
<input type="text" class="form-control" id="furniture" placeholder="Enter 
number of Furniture Pads.">
</div>
<button type="submit" onClick='addLocation(); return false;' id='button' 
class="btn btn-primary">Submit</button>
</form>
<tbody id='masterTable'>

</tbody>
</table>
</body>

<script>
const button = document.getElementById('button');
const dropdown = document.getElementById('dropdown').value;
const htruck = document.getElementById('handtrucks').value;
const fpad = document.getElementById('furniture').value;


function addLocation() {
let masterList = document.getElementById('masterTable');
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
var handTruck = document.getElementById('handtrucks').value;
var furnPads = document.getElementById('furniture').value;
var row = document.createElement("tr");
var locationEntry = document.createElement('td');
var htEntry = document.createElement('td');
var fpEntry = document.createElement('td');
row.appendChild(locationEntry);
locationEntry.appendChild(document.createTextNode(strUser));
row.appendChild(htEntry);
htEntry.appendChild(document.createTextNode(handTruck));
row.appendChild(fpEntry);
fpEntry.appendChild(document.createTextNode(furnPads));
masterList.appendChild(locationEntry);
masterList.appendChild(htEntry);
masterList.appendChild(fpEntry);
}
</script>
</html>

Answer №1

The issue lies in your code where you are appending a <td> element to a <tbody> without a <tr>. I recommend simplifying your html-code by creating a basic string instead of using multiple variables like this:

let row = document.createElement('tr');
let html = '<td>' + value + '</td><td>' + value1 + '</td><td>' + value2 + '</td>';
row.innerHTML = html;
masterList.appendChild(row);

Answer №2

Try using

masterList.appendChild(row);

rather than

masterList.appendChild(locationEntry);
masterList.appendChild(htEntry);
masterList.appendChild(fpEntry);

Answer №3

There were a few bugs found in the code, so I took the liberty of commenting out the problematic line. Additionally, I noticed that an opening <table> tag was missing, so I added it back in here. Other than those adjustments, this answer represents the complete version of @Lab Lab's original response.

<!DOCTYPE html>
<html>
<link>
</link>

<head>
</head>

<body>
  <div class="d-flex">

    <div>
      <select id="ddlViewBy">
        <option value="0310">XXXX-10</option>
        <option value="4610" selected="selected">XXXX-10</option>
        <option value="4610">XXXX-10</option>
      </select>
    </div>
  </div>
  <form>
    <div class="form-group">
      <label>Hand Trucks</label>
      <input type="text" class="form-control" id="handtrucks" placeholder="Enter
number of Hand Trucks.">
    </div>
    <div>
      <label>Furniture Pads</label>
      <input type="text" class="form-control" id="furniture" placeholder="Enter
number of Furniture Pads.">
    </div>
    <button type="submit" onClick='addLocation(); return false;' id='button' class="btn btn-primary">Submit</button>
  </form>
  <table>
  <tbody id='masterTable'>

  </tbody>
  </table>
</body>

<script>
  let button = document.getElementById('button');
  // const dropdown = document.getElementById('dropdown').value;
  let htruck = document.getElementById('handtrucks').value;
  let fpad = document.getElementById('furniture').value;
  let masterList = document.getElementById('masterTable');

  function addLocation() {
    var e = document.getElementById("ddlViewBy");
    var strUser = e.options[e.selectedIndex].value;
    var handTruck = document.getElementById('handtrucks').value;
    var furnPads = document.getElementById('furniture').value;
    var row = document.createElement("tr");
    var locationEntry = document.createElement('td');
    var htEntry = document.createElement('td');
    var fpEntry = document.createElement('td');
    row.appendChild(locationEntry);
    locationEntry.appendChild(document.createTextNode(strUser));
    row.appendChild(htEntry);
    htEntry.appendChild(document.createTextNode(handTruck));
    row.appendChild(fpEntry);
    fpEntry.appendChild(document.createTextNode(furnPads));
    masterList.appendChild(row);
  }
</script>

</html>

Answer №4

Your code seems to have a few issues like formatting errors, incomplete html tags, and the order of dom manipulation methods. However, I can understand what you were trying to achieve.

In an attempt to replicate a solution similar to the code you provided, I created a new table row of data from each input using vanilla JS when the button is clicked.

document.getElementById('button').addEventListener('click', (e) => {
  e.preventDefault();
  addLocation();
});

function addLocation() {
  // fetch information
  const userOpts = document.getElementById('ddlViewBy');
  const user = userOpts.options[userOpts.selectedIndex].value;
  const htruck = document.getElementById('handtrucks').value;
  const fpad = document.getElementById('furniture').value;
  // create a table row
  const row = document.createElement('tr');
  // create table data cells
  const userTd = document.createElement('td');
  const htruckTd = document.createElement('td');
  const fpadTd = document.createElement('td');
  // insert input data into table cells
  userTd.innerText = user;
  htruckTd.innerText = htruck;
  fpadTd.innerText = fpad;
  // append cells to the row
  row.appendChild(userTd);
  row.appendChild(htruckTd);
  row.appendChild(fpadTd);
  // add the new row to the master table
  document.getElementById('masterTable').appendChild(row);
};
table, td, tr {
  border: 1px solid black;
  border-collapse: collapse;
}
td {
  padding: 0 3px;
}
<div class="d-flex">

  <div>
    <select id="ddlViewBy">
      <option value="0310">XXXX-10</option>
      <option value="4610" selected>XXXX-10</option>
      <option value="4610">XXXX-10</option>
    </select>
  </div>
</div>
<form>
  <div class="form-group">
    <label>Hand Trucks</label>
    <input type="text" class="form-control" id="handtrucks" placeholder="Enter 
    number of Hand Trucks.">
  </div>
  <div>
     <label>Furniture Pads</label>
    <input type="text" class="form-control" id="furniture" placeholder="Enter 
    number of Furniture Pads.">
  </div>
    <button type="submit" id='button' 
  class="btn btn-primary">Submit</button>
</form>
<table class="tblclass" id='masterTable'>

</table>

I hope this explanation clarifies things for you

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

The Express API is throwing an error because it cannot access the property 'count' of an undefined value

Issue occurs when calling the List API after successfully calling the Create Option API in the Express (Node + MongoDB) API. The error message received is: Cannot read property 'count' of undefined. Below is the code snippet from the Option Contr ...

the speed of accessing an array in JavaScript

Assuming there is a javascript array1 with 10,000 elements, what would be the time complexity of: var array2=new array(); array2.push(array1); and what about the time complexity of var object={}; object['array2']=array1; Are both operatio ...

I have successfully integrated my custom external JavaScript code with React Router, and everything is working

Assistance Needed! I am working on a project that consists of 4 pages, one of which is the About page. I am using react-router to manage the paths and contents between these pages through their respective links. import React from 'react'; impo ...

How can I retrieve the contents of input fields and showcase them in a dialog box?

<dialog> label id="show" label label id="show1" label </dialog> var x = document.getElementById("name").value; x = document.getElementById("show").innerHTML; var y = document.getElementById("matrix").value; y = document.getElementById("sho ...

Attempting to embed Text components within another Text component, each with distinct font styles. Unfortunately, in one instance, the line height is causing certain text to be clipped

I am working on a React Native application and experimenting with creating styled text elements. I wanted to have different styles for each word in a sentence, so I nested Text components with different styles inside one another. For example: <T ...

Is there a way to align all the values in the center of the row, while ensuring that the div above the row does not have the same width as the row below it? If so, how

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src= ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Having trouble accessing the dashboard after uploading a document to Firestore

I am currently working on a project where I need to upload an audio file to Firebase storage and also add document data related to the audio file in Firestore database. The process involves recording the audio, uploading it to Firebase storage, submitting ...

Tips for making a rounded bottom image slider with react-native?

Is there a way to design an image slider similar to this with rounded bottom images? ...

WebVTT captions on a Chromecast receiver as the default option

Trying to set up closed captions for chromecast using the default Chrome sender app but it's not working. The code is similar to the sample provided in the docs, seen here. I've shared a snippet that might be too sandboxed, view it on a normal ht ...

Running an Express middleware function

While watching a tutorial on the Express framework, I came across some interesting code used by the instructor for handling requests. Here is how the route is set up: router.route('/').post(authController.restrictTo('admin', 'l ...

The event handler for clicking on the inner <li> element is not being triggered

I am encountering an issue in my React project, The problem lies within a menu structure that contains nested sub-menus. Here is the snippet of code: <ul id="main-menu-navigation" data-menu="menu-navigation" ...

The looping mechanism in Angular is not being updated because of how the $mdDialog from Material Design is being implemented

After reviewing my previous post on Angular loop is not updating, I made a slight modification to the code by incorporating a dialog box for user interaction. The only change in my app.js file was the addition of a $mdDialog box directive. Therefore, the ...

How can JavaScript be used to populate a textbox value from a URL parameter?

After a user submits the script below, I want to redirect them back to the same page and fill in the dropdown menu and input box with values from the URL parameters. However, the fields are not populating after the redirect. Additionally, I need to remove ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

CKEditor not functioning properly when generated using AJAX and PHP in JavaScript file

I am facing an issue where I am using PHP and AJAX to generate a CKEditor textarea. The CKEditor JavaScript files are included in the main HTML file, and the PHP and AJAX functionalities are working correctly. However, when the form is displayed, the CKEdi ...

Using cleave.js as a field in Formik: A step-by-step guide

Currently, I am attempting to implement a Cleave (visit for more information) as a Field within a Formik form. While standard components like text inputs are functioning correctly, the value change in the Cleave component is not being captured and is rese ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...