How can I add rows to the tbody of a table that is already inside a div container?

I have an existing table and I want to append a tbody element to it. Below is an example of the HTML table:

<div id="myDiv">
    <table class="myTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Last</th>
                <th>First</th>
                <th>DOB</th>
                <th>Nickname</th>
            </tr>
        </thead>
    </table>
</div>

Below is my JavaScript/JQuery code:

var divID = $('#myDiv table.myTable');
var tbl = "<tbody>"; 
for(var i=0; i < numRecs; i++){
    var jsRec = obj.DATA[i];
    tbl += "<tr id='lookup_"+i+"'>";
    tbl += "<td>"+decodeURIComponent(jsRec.ID)+"</td>";
    tbl += "<td>"+decodeURIComponent(jsRec.LAST)+"</td>";
    tbl += "<td>"+decodeURIComponent(jsRec.FIRST)+"</td>";
    tbl += "<td>"+decodeURIComponent(jsRec.DOB)+"</td>";
    tbl += "<td>"+decodeURIComponent(jsRec.NICKNAME)+"</td></tr>";          
}
tbl += "</tbody>";
divID.append(tbl);
$.alert(divID,'Main Menu',1000,600); //JQuery dialog box that takes html variable, title, width and height

The issue I'm facing is that the content in my dialog box appears blank with this code. If anyone can help identify where my code is breaking, please let me know. Thank you.

Answer №1

It seems that the <tr> tag is not properly closed in your loop, resulting in unclosed table rows. jQuery checks HTML validity before adding it to the DOM, so it may be failing silently when attempting to use the append method.

Answer №2

To enhance clarity and organization in the element creation process, consider breaking it down into smaller sections, as demonstrated below. This approach makes it easier to pinpoint any issues that may arise along the way. One potential refinement involves substituting sampleData[i]["id"] with decodeURIComponent(jsRec.ID), among other tweaks. The sampleData Array was solely crafted for illustrative purposes. Another suggestion is to potentially incorporate decodeURIComponent() within a loop to handle each property of your object.

(function($) {
  $(document).ready(function() {
    var sampleData = [{
      id: 1,
      last: "lst",
      first: "first",
      DOB: "IDK",
      nickname: "nick"
    }];

    var divID = $('#myDiv table.myTable tbody');
    var current, row, cell;


    for (var i = 0; i < sampleData.length; i++) {
      row = $("<tr></tr>"); //Generate a new row
      cell = $("<td></td>").html(sampleData[i]["id"]); //Craft a cell
      row.append(cell); //Attach the cell
      cell = $("<td></td>").html(sampleData[i]["last"]);
      row.append(cell);
      cell = $("<td></td>").html(sampleData[i]["first"]);
      row.append(cell);
      cell = $("<td></td>").html(sampleData[i]["DOB"]);
      row.append(cell);
      cell = $("<td></td>").html(sampleData[i]["nickname"]);
      row.append(cell);
      divID.append(row); //Insert Row into the Table
    }
  });

})(jQuery);
td,
th,
tr {
  border: 1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv">
  <table class="myTable">
    <thead>
      <tr>
        <th>ID</th>
        <th>Last</th>
        <th>First</th>
        <th>DOB</th>
        <th>Nickname</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>

In the final stages, you may encounter challenges with

$.alert(divID,'Main Menu',1000,600);
, but simply incorporating a toString() or similar adjustment could resolve it.

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

Spring guide: Updating form elements within a JSP page with Spring framework

I am working on a JSP page that includes a form. I want to create a functionality where if a user enters a value in a text box for "NO.Of Units", additional text boxes should appear below to input the names of each unit based on the number entered. For e ...

The content within the iframe is not properly sized

I'm facing a challenge with an iframe that has a fixed height of 1000px which I am unable to adjust. I would like the content to fit within the iframe. As a CSS novice, I need some guidance on how to achieve this. Thank you! <iframe style="height: ...

What is the best way to adjust the height of a Div to be 100%?

I've been struggling to make the .footer and the div .content have a height of 100%. While I know how to get the footer to stick at the bottom, I can't seem to make the content div reach the bottom of the page. Increasing the min-height on the co ...

Seeking a regular expression to identify special characters appearing at the beginning of a string

I'm looking to update my current regex pattern to include special characters at the beginning of a string value. Here's what I have right now: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+.]{ ...

PHP script output continuously responded with AJAX

Encountering an issue with the AJAX response from my PHP script... I've set up a "Status" div to display the response of the PHP script. It currently only shows the response once the entire script has finished, but I would like it to show each echo " ...

Adding a dynamic style programmatically to an element created using createElement in Vue: A guide

I have a canvas element that is created programmatically and I am looking to apply a reactive style to it. canvas = document.createElement('canvas') //Apply style this.$refs.parentElement.appendChild(canvas) In a typical scenario, you would u ...

Styles and CSS have been successfully loaded, however, the content is not appearing

After attempting to import a web HTML CSS template into my self-made MVC, I encountered an issue. While the template works properly on its own, it fails to connect to the CSS files and display proper styles when accessed through my controller. Instead, onl ...

Facing challenges in implementing a logic to showcase an intricate page on express.js (node.js) platform

Having trouble setting up a functional logic to display a detailed page showcasing the post title, image, and details. Currently, I've successfully created a list page that displays all the posts by the logged-in user with the title, image, and detail ...

Running Python code with Selenium on an Azure server

While using Selenium to open web pages and extract content, I encountered an issue on my Azure server (which is command line based) as it does not support Chrome or Firefox browsers. Therefore, I am seeking an alternative method to run Python-based Seleniu ...

I'm encountering an error while attempting to parse the XML file

Need help with ajax call $j.ajax({ url: "http://www.earthtools.org/timezone/40.71417/-74.00639", dataType: "jsonp", complete: function(data){ console.log(data); } }); The URL returns XML, but I'm trying to use JSONP to avoid cross-site s ...

Sort by characteristics of embedded array - Knockout

I'm struggling with filtering a nested array using Knockout. My goal is to filter the array by both 'tag-names' and 'name'. For example, searching for 'whal' should display all objects that contain a tag with that name ...

What is the best way to showcase the organized values according to their attributes?

How can I sort and display values based on their properties? For example, I want to only show the likes and convert them back into an object so I can use them as properties. I apologize for the previous edit, this is the updated version with a working sim ...

Using Jquery to display text when the condition is not met

Here is the code snippet I am currently working with: http://jsfiddle.net/spadez/mn77f/6/ I am trying to make it display a message when there are no fields (questions) present. I attempted to achieve this by adding the following lines of code: } else ...

Hovering in Javascript

Imagine I have the following code snippet: <div class="class1"> ... random content </div> I want to use JavaScript so that when I hover over that div, a CSS attribute is added: background-color:#ffffe0; border:1px solid #bfbfbf; This is a ...

What could be the reason behind the occurrence of Content-Length=0 for jQuery AJAX POST requests in the IE 11 browser without

I've been developing a Spring MVC based web application. Here are the details of my environment :- Java 1.8.0_162 (64 bit), Spring 4.3.1, Apache Tomcat 8.0.49, Waffle-1.8.3 for SSO, jquery-1.11.3 and Google Charts API. I have included the following ...

Determining when ng-repeat has completed in Angular JS

Is there a way to determine when ng-repeat has completed populating the values in the markup? Since I have numerous values, it may take some time for the rendering process. NG <ul > <li data-ng-repeat="item in values"> ...

Creating a layered effect by overlaying one image on top of another in an HTML5

Currently, I am facing an issue with drawing a level field inside my canvas. The images of the tank and enemies are being drawn underneath the field image, which is causing some problems as they should actually be moving above the field. Here is a link t ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Having issues with Vue.js v-repeat not displaying any content

I have just started learning about vue.js. I attempted to display a simple list, but it is not showing anything. Here is my code: <html> <head> <title>VUE Series</title> <link rel="stylesheet" type="text/css" ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...