Adding data to a bootstrap table dynamically with javascript

I came across some other posts that discuss a similar issue using jQuery, but I'm determined to stick with pure JavaScript for this. My goal is to construct a table using Bootstrap, however, I've hit a roadblock when it comes to adding new data to the table. The table header gets created just fine, but the rows with the actual data end up below the header in an unorganized manner.

Here's the HTML:

<div id = specificFailureCountTable-js></div>

And here's the JavaScript code:


let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js"); 
let data = [["machineA",15],["machineB",54],["machineC",26]];

// Create the table header
tableData.innerHTML = `
<table class="table table-striped" id = "myTable">
  <thead>
    <tr>
      <th scope="col">${filterText}</th>
      <th scope="col">Count</th>
    </tr>
  </thead>
  <tbody>
`;

// Iterate over the data and add rows to the table
for(i = 0; i < data.length; i++){
    tableData.innerHTML = tableData.innerHTML +
    `<tr>
      <th scope="row">${i}</th>
      <td>${data[i][0]}</td>
      <td>${data[i][1]}</td>
    </tr>`
}

// Close off the table
tableData.innerHTML = tableData.innerHTML +
  `</tbody>
  </table>`
  ;

Answer №1

To ensure your table is properly constructed without breaking the DOM, it's important to first define a variable that will hold your table data. Once you have appended all necessary data to this variable, assign it to tableData.innerHTML:

let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js"); 
let data = [["machineA",15],["machineB",54],["machineC",26]];

//set header of table
let table = `
<table class="table table-striped" id = "myTable">
  <thead>
    <tr>
      <th scope="col">${filterText}</th>
      <th scope="col">Count</th>
    </tr>
  </thead>
  <tbody>
  `;
  //create//append rows
for(i = 0; i < data.length; i++){
    table = table +
    `<tr>
      <th scope="row">${i}</th>
      <td>${data[i][0]}</td>
      <td>${data[i][1]}</td>
    </tr>`
}
//close off table
table = table +
  `</tbody>
  </table>`
  ;

tableData.innerHTML = table;

Additionally, remember that you can use table += 'xxx' as a shortcut for table = table + 'xxx'

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

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Say goodbye to document.write?

There is a function defined below: function loadJavaScript(src) { document.write('<' + 'script src="' + src + '"' + ' type="text/javascript"><' + '/script>'); } This ...

When attempting to duplicate a project from Bitbucket and working in VS Code, I encountered several errors and warnings while running npm install

I have a project on Bitbucket that I'm trying to clone. The project is quite old, about 3 years old, so some packages may be outdated. However, when I run npm install, I am seeing a lot of warnings and errors. Additionally, the project was originally ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

What steps should I follow to utilize my spotify api token effectively?

Currently, I am working on developing a random playlist generator using the Spotify API. However, when I retrieve information from their server, I receive a 401 error code. I have managed to obtain an access token by following a tutorial. My main concern ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance.https://i.sstatic.net/EHdMo.png ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

Dropdown does not populate with data

HTML content <select class="form-control" tabindex="-1" id="superId" name="superId[]" multiple="multiple" required="required" data-bind="options: SupArray, optionsText: ' ...

Best way to position camera to look at or above a specific location on a sphere in Three.js

Is there anyone out there with a suggestion on how to position the camera so it is directly facing upwards towards a specific point on the sphere? LATEST DEVELOPMENT It turns out that Radio's solution was spot on. Upon further investigation, I disco ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Hide a division when either the body or another division is clicked

<div id="container"> <div class='sub1'></div> <div class='sub2'></div> <div class='part1'></div> <div class='part2'></div> </div> When yo ...

Display the next page once two distinct service requests have been received

When I need to display a page after retrieving data from two different services, service1 and service2, how can I achieve this without nesting the second service call inside the first one? Instead of chaining the service calls, I want to make separate req ...

Tips for extracting the href value in Jest test when using React Router:

Exploring React JS for the first time and currently working on creating a test case using Jest to verify the link in my component. I am utilizing react-router and within the link, I have used <LINK to="{{pathname: link}}" />Link</LINK>. My vers ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

The Bootstrap carousel slider is functioning properly, however, the images are not displaying

I am experiencing an issue with my carousel. I have been developing a project and utilizing the bootstrap-4 carousel slider. It functions properly when I run it on my localhost, displaying all the images as expected. However, after publishing the project o ...

Tips for choosing and deselecting data using jQuery

Is there a way to toggle the selection of data in my code? Currently, when I click on the data it gets selected and a tick image appears. However, I want it so that when I click again on the same data, the tick will disappear. How can I achieve this func ...

Loading React.js components before data fetch is complete

My app is encountering an issue where it renders before the fetch operation is completed, resulting in incorrect rendering. Below is the code snippet: componentWillMount() { fetch('http://localhost:8081/milltime/login?users='+this.state.e ...

Link numerous number-type inputs together

I'm looking to create a form with 6 input fields of type number. Each label will have specified min and max values. The challenge is that if I set one field to be between 0-50, for example in red, then the next field in yellow can't be from 49-70 ...