Guide to dynamically add tr element using CSS to a table

While using the $.each function in jQuery, I am retrieving data and adding it to a table in the following manner:

 $.each(segment, function (index, innerSegment) {
 var tr;
 tr = $('<tr/>');
 tr.append("<td>" + segment[i].Airline.AirlineName + "</td>");

 tr.append("<td>" + segment[i].ArrivalTime + "</td>");
 tr.append("<td>" + segment[i].Origin + "</td>"); 

 tr.append("<td>" + segment[i].DepartureTime + "</td>");
 tr.append("<td>" + segment[i].Destination + "</td>"); 

 tr.append("<td>" + segment[i].Duration + "</td>");
 tr.append("<td>" + segment[i].publishedFare + "</td>");
 $('#tableId').append(tr);
}

Although I am successfully receiving data from the $.each loop, all the data is getting appended one after the other.

I would like the data to be displayed as shown in this example on jsfiddle: https://jsfiddle.net/1pbso9jt/

The structure of my table is as follows:

<table id="tableId">
     <tr>   
       </tr>
 </table>

Answer №1

What do you think about this version:

let table = $('#tableId');
$.each(segment, function (index, innerSegment) {
  let rows = '<tr><td rowspan="4" width="25%">' + segment[i].Airline.AirlineName + "</td>";
  rows += '<td width="25%">' + segment[i].ArrivalTime + "</td>";
  rows += '<td rowspan="4" width="25%">&nbsp;</td>';
  rows += '<td rowspan="4" width="25%">' + segment[i].publishedFare + "</td></tr>";
  rows += "<tr><td>" + segment[i].Origin + "</td></tr>"; 
  rows += "<tr><td>" + segment[i].DepartureTime + "</td></tr>";
  rows += "<tr><td>" + segment[i].Destination + "</td></tr>"; 

  table.append(rows);
});

Check out the example fiddle with the each commented out

Explore the updated fiddle with your data

Answer №2

To optimize your code, consider integrating your jsfiddle with the loop as shown below:

$.each(segment, function (index, innerSegment) {
  var output;
  output = $('<table border="1" style="width:100%"><tr>');
  output.append("<td rowspan="4" style="width:25%">" + segment[i].Airline.AirlineName + "</td>");
  output.append("<td height="58">" + segment[i].ArrivalTime + "</td>");
  ...
  and so on
  ...
  $('#tableId').append(output);
}

Answer №3

Give this a try:

$.each(segment, function (index, innerSegment) {
 var row;
 row = "<tr/>";
 row += "<td>" + segment[i].Airline.AirlineName + "</td>";

 row += "<td>" + segment[i].ArrivalTime + "</td>";
 row += "<td>" + segment[i].Origin "</td>";

 row += "<td>" + segment[i].DepartureTime + "</td>";
 row += "<td>" + segment[i].Destination "</td>"; 

 row += "<td>" + segment[i].Duration + "</td>";
 row += "<td>" + segment[i].publishedFare "</td>";
 $('#tableId').append(row);
}

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

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

issues with jquery functionality on mobile devices

I'm currently working on a website where I've implemented a jQuery script to dynamically load specific parts of an HTML page with an ID of 'guts' into the main content area. The goal was to keep the menu consistent while only changing t ...

Personalize the layout for vertical table headings and table information

I need help with a table that has vertical headers. I want to remove the extra space within the table header and data cells. Here is the code for my table: <table> <tr> <th class="field">Item ID Number:</th> < ...

How can a method inside an object property of the same class be invoked in JavaScript?

I'm faced with a bit of confusion here. I have a class property called hotspot of type object, declared as follows: Cannon.prototype.hotspot = {stuff: this.blah(...) }; The method blah() is actually a prototype of the same 'class': Canno ...

Submit your Alpaca info without leaving this page!

Currently, I am in the process of constructing a form using PHP and ALPCA, which involves jquery and ajax. However, I seem to be encountering some difficulty when it comes to file submission while staying on the same page. Despite attempting various recomm ...

Changing the animation associated with a hover action - tips and tricks!

My navigation header includes links to various websites, some of which are displayed as drop-down menus. I have implemented an animation and style change on hover to visually indicate the active link and display all available options in case of a dropdown ...

The server is unable to process the request with parameters for the specified URL

I've been encountering an error every time I try to post something. articlesRouter.post('articles/:target', async (req, res) => { const target = req.params.target.replaceAll("_", " ") const article = await Arti ...

Troubleshooting: Browser fails to update after CSSStyleRule modification using JavaScript

When making changes to CSS properties of elements using JS methods like CSSStyleSheet, insertRule, deleteRule, or CSSStyleRule.style.setProperty(), I noticed that the underlying CSS is updated but the page does not reflect these changes immediately. The c ...

Insert an HTML tag into JSLint

Is there a way to include an HTML tag in JSLint's list of recognized tags? I'm encountering some errors with the following message: JSLint: Unrecognized tag 'foo'. How can I make the foo tag recognized by JSLint as a valid HTML tag? ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Angular js: Understanding the use of "this" within the ng-if function

Is there anyone who can assist me with the following question: How do I access the "this" element within the ng-if (in my example, the classname is "class_to_obtain" of the span element)? http://plnkr.co/edit/0s7PCWN2fJ8sJpFSJssV HTML ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

The nested directive link function failed to execute and the controller was not recognized

Apologies in advance for adding to the sea of 'mah directive link function isn't called!' posts on Stack Overflow, but none of the solutions seem to work for me. I have a directive named sgMapHeader nested inside another directive called sg ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

"Struggling to upload an image using Selenium WebDriver because the element is not visible? Here are

ff.findElementByxpath(//object[@ id='slPlugin2']).click(); The element is not being recognized. Can you also provide guidance on how to upload media through webdriver? <table class="imgTable photoTable" cellspacing="0"> <div id="file ...