MattG
MattG

Reputation: 1932

Append to bootstrap table using javascript

I found a few other posts that seem to address this using jquery, but I would like to use javascript only. I would like to create a table using bootstrap but can't seem to figure out how to append new data to the table. It is creating the header, but then just dumping the items I want as rows below the table header.

html

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

js

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

//set header of table
tableData.innerHTML = `
<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++){
    tableData.innerHTML = tableData.innerHTML +
    `<tr>
      <th scope="row">${i}</th>
      <td>${data[i][0]}</td>
      <td>${data[i][1]}</td>
    </tr>`
}
//close off table
tableData.innerHTML = tableData.innerHTML +
  `</tbody>
  </table>`
  ;

Upvotes: 0

Views: 4200

Answers (1)

jcubic
jcubic

Reputation: 66490

Just use variable that will define your table append to that variable and at the end when it would be ready assign to to tableData.innerHTML, otherwise you will have broken DOM (not sure what the output would be but it maybe different depending on browser):

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;

And one side note: you can use table += 'xxx' as shortcut for table = table + 'xxx'

Upvotes: 1

Related Questions