Bootstrap table styling fails to be applied to dynamically generated tables via JavaScript

Hey there, I'm diving into the world of website development for the first time, just getting started a couple of days back.

Although I have some experience with Python and C# programming, I'm facing challenges in generating an HTML table using JS and applying Bootstrap CSS styling to it.

Unfortunately, I can't seem to make it work.

This is what I'm currently getting:

https://i.sstatic.net/dSRDN.png

And this is what I'm aiming for:

https://i.sstatic.net/GZ1S3.png

My goal is to achieve a style similar to this (simplified from: w3schools)

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>

    <div class="container">
      <h2>Basic Table</h2>
      <p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>            
      <table class="table">
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
          </tr>
          <tr>
            <td>John</td>
            <td>Doe</td>
            <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a404542446a4f524b475a464f04494547">[email protected]</a></td>
          </tr>
      </table>
    </div>

    </body>
    </html>

This is how my current HTML page structure looks:

<!DOCTYPE html>
<html>
    <head>
        <title>CSVParser</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        </head>

    <body>
        <div class="container">
        <script type="text/javascript" src="../scripts/csvToHtml.js"></script>
        <form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
            <input type="file" id="myFile" name="myFile"><br>
            <input type="submit" name="submitMe" value="Process File">
        </form>

        <table id="myTable" class="table"></table>
        </div>
        </body>
</html>

Also, here's my JavaScript function that processes the file input and generates the HTML table:

function processFile() {
 var fileSize = 0;
 var theFile = document.getElementById("myFile").files[0];
 if (theFile) {
     var table = document.getElementById("myTable");
     var headerLine = "";
     var myReader = new FileReader();
     myReader.onload = function(e) {
         var content = myReader.result;
         var lines = content.split("\r");
         for (var count = 0; count < lines.length; count++) {
             var row = document.createElement("tr");
             var rowContent = lines[count].split(",");
             for (var i = 0; i < rowContent.length; i++) {
                 if (count == 0) {
                     var cellElement = document.createElement("th");
                 } else {
                     var cellElement = document.createElement("td");
                 }
                 var cellContent = document.createTextNode(rowContent[i]);
                 cellElement.appendChild(cellContent);
                 row.appendChild(cellElement);
             }
             myTable.appendChild(row);
        }
    }
    myReader.readAsText(theFile);
 }
 return false;
}

The CSV data file I'm loading has the following content:

TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144

And this is the HTML table generated after processing the file:

<table id="myTable" class="table">
    <tr>
        <th>TestA</th>
        <th>TestB</th>
        <th>TestC</th>
        <th>TestD</th>
    </tr>
    <tr>
        <td>Alpha</td>
        <td>0.551608445</td>
        <td>0.807554763</td>
        <td>54.8608682</td>
    </tr>
    <tr>
        <td>Beta</td>
        <td>0.191220409</td>
        <td>0.279946678</td>
        <td>57.55254144</td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>

Answer №1

You need to include a <tbody> element around all your <tr> elements. Once you add this, your layout will work correctly.


Your code has been modified. Below is a functioning example:

<!DOCTYPE html>
<html>
    <head>
        <title>CSVParser</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        </head>

    <body>
        <div class="container">
            <form action="#" name="myForm" id="aForm" method="POST">
                <input type="file" id="myFile" name="myFile"><br>
                <input type="button" name="submitMe" value="Process File" onclick="processFile();">
            </form>
            <table id="myTable" class="table"></table>
        </div>
        
        </body>
        <script type="text/javascript">
            function processFile() {
                 var fileSize = 0;
                 var theFile = document.getElementById("myFile").files[0];
                 if (theFile) {
                     var table = document.getElementById("myTable");
                     var headerLine = "";
                     var myReader = new FileReader();
                     myReader.onload = function(e) {
                         var content = myReader.result;
                         var lines = content.split("\r");
                         var tbody = document.createElement("tbody");

                         for (var count = 0; count < lines.length; count++) {
                             var row = document.createElement("tr");
                             var rowContent = lines[count].split(",");
                             for (var i = 0; i < rowContent.length; i++) {
                                 if (count == 0) {
                                     var cellElement = document.createElement("th");
                                 } else {
                                     var cellElement = document.createElement("td");
                                 }
                                 var cellContent = document.createTextNode(rowContent[i]);
                                 cellElement.appendChild(cellContent);
                                 row.appendChild(cellElement);
                             }
                             tbody.appendChild(row);
                        }

                        table.appendChild(tbody);
                    }
                    myReader.readAsText(theFile);
                 }

                 return false;
            }
        </script>
</html>


Functioning example without the need to upload a file

<!DOCTYPE html>
<html>
    <head>
        <title>CSVParser</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        </head>

    <body>
        <div class="container">
            <form action="#" name="myForm" id="aForm" method="POST">
                <textarea id="myFile" name="myFile">TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144</textarea><br>
                <input type="button" name="submitMe" value="Process File" onclick="processFile();">
            </form>
            <table id="myTable" class="table"></table>
        </div>
        
        </body>
        <script type="text/javascript">
            function processFile() {
                var table = document.querySelector("#myTable");
                var content = $("#myFile").val();
                var lines = content.split("\n");
                var tbody = document.createElement("tbody");

                for (var count = 0; count < lines.length; count++) {
                    var row = document.createElement("tr");
                    var rowContent = lines[count].split(",");

                    for (var i = 0; i < rowContent.length; i++) {
                        if (count == 0) {
                            var cellElement = document.createElement("th");
                        } else {
                            var cellElement = document.createElement("td");
                        }

                        var cellContent = document.createTextNode(rowContent[i]);
                        cellElement.appendChild(cellContent);
                        row.appendChild(cellElement);
                    }

                    tbody.appendChild(row);
                }

                table.appendChild(tbody);

                return false;
            }
        </script>
</html>


ALSO! Be aware that you are using myTable.appendChild(row); in your code without initializing a myTable variable.

Answer №2

It's crucial to load your JavaScript script right before the closing </body> tag.
By doing so, you ensure that the browser has parsed all the necessary elements before the script queries them.

<body>
  <div class="container">
  
  <form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
    <input type="file" id="myFile" name="myFile"><br>
    <input type="submit" name="submitMe" value="Process File">
  </form>

  <table id="myTable" class="table"></table>
  </div>
  <!-- This is key -->
  <script type="text/javascript" src="../scripts/csvToHtml.js"></script> 
</body>

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

Having trouble scrolling on a Chrome browser with the Muse website?

My significant other is having some trouble with her muse-created website at . It seems to have an issue scrolling horizontally on Chrome, but works fine on Safari and Edge. The site is part of a university project and she hopes it will eventually look lik ...

Website experiences technical difficulties but database remains up-to-date

I previously made a similar post, but I have not resolved the issue yet. Here is the output from my terminal: 23 Dec 22:31:23 - Serving request for url[GET] /team 23 Dec 22:31:23 - Successfully created team with Name : Japan 23 Dec 22:31:23 - Serving re ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

Using ReactJS and Redux to dispatch notifications

I have a query regarding displaying notifications for successful or failed user registration actions. Utilizing Redux, I've implemented the following action page: export function registerUserFail(error){ return { type:REGISTER_USER_FAIL, ...

Binding attributes in knockoutjs following an AJAX request

The objective Incorporate the attr binding of KnockoutJS following an AJAX call. The dilemma Check out the code snippet below: $.ajax({ url: "/Products/List?Output=JSON", dataType: "json", success: function (data) { $.each(data, fun ...

Incorporating tawk.to into a Nuxt/Vue application

Has anyone had success implementing tawk.to in a Nuxt application? I took the initiative to create a file called "tawk.js" in my plugin folder and added the following code: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date() (function () { ...

What steps can I take to ensure my header image adjusts properly for different screen sizes?

Currently, I am working on creating a website for a friend using an exquisite premium Wordpress theme. Despite having paid for the theme, the designer is unwilling to assist with customization. You can view the site in progress at www.zerocarbonfood.co.uk ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Display the latest distinct records in Vue.js

I've hit a roadblock in my project. @StephenThomas kindly assisted me with this issue: Vue.js only show objects with a unique property but I still need to make some adjustments. My current task involves creating a leaderboard for a game using Firest ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

Refresh the page when the dropdown selection is changed and send the new value

I'm currently working on a page that includes a dropdown menu. My goal is to have the page reload after selecting an option from the dropdown so that it returns to the same page with the selected value passed through. Here's the PHP code for th ...

Issues with angular-strap popover's onBeforeShow function not functioning as expected in Angular

I am currently utilizing the angular-strap popover feature. To learn more about it, visit According to the documentation, when an onBeforeShow function is provided, it should be called before the popover is displayed. However, I am experiencing issues wit ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...

How can one determine the proper size for a border?

Can the border of a div be larger than the actual dimensions of the div itself? For instance, if the div is 10x10 in size, is it possible to have a border that is 20x10? ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

What is the best way to eliminate duplicate data from a JSON file?

In the code snippet below, there is a function that queries and retrieves data from a getjson. The issue at hand is how to filter out repeated results so that they do not appear. Is there a way to prevent duplicate data from being displayed? var cuit ...

Is there a way to implement this toolbar in Ionic Angular?

https://i.sstatic.net/sGd1o.png I am looking to replicate the toolbar shown in the image above using Ionic. As a beginner in Ionic development, I am finding it challenging to translate the design into code. I attempted to use a grid layout, but the varyin ...

The functionality of HTML labels may be limited when used in conjunction with AJAX

I am using Ajax to load an HTML page and encountering a problem with the label not working properly when associated with a checkbox. Here is the data: <input type="checkbox" name="dis_net" id="dis_net" value="1" /> <label for="dis_net">Test< ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Disable text input in Flatpickr and remove the default iPhone calendar

We are facing an issue with the iPhone and iPad when using flatpickr for our calendars. When the calendar is opened, the cursor automatically focuses on the text box, triggering the default iPhone calendar to appear below. This problem does not occur on An ...