Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" column headings.

Issue: -The data within the array seems to be exceeding its boundaries or rather there are no specific boundaries established within the table headers "Date Name Address Amount". Instead of creating a new entry after the "Amount" header, it simply adds the new record on the same line. I intend for it to wrap back around to start a new record row underneath the "Date" column header so that each date value in the array corresponds with the "Date" header, name value with the "Name" header...etc as shown in the example below... Example: With 4 headers (Date, Name, Address, Amount) I expect the next date entry to appear under the "Date" header. It is currently placing subsequent date values on the same row without transitioning to a new record row. Code provided below. Date Name Address Amount

index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Winch - Lab 10</title>
        <script src="arrays.js" type="text/javascript"></script>
        <script type="text/javascript">
            function totalContributions()
            {
                var totalAmount = 0;
                for (var i = 0; i < amount.length; i++)
                    totalAmount = totalAmount + amount[i];
                return totalAmount;
            }

        </script>
    </head>
    <body>
     <table id="donations">
         <tr>
             <th>Date</th>
             <th>Name</th>
             <th>Address</th>
             <th>Amount</th>
         </tr>
         <script>
             for (var x=0; x < amount.length; x++){
                 if (x%2==0){
                    document.write("<tr>");
                 } else {
                     document.write("<tr class='stripe'>");
                 }
                  document.write("<td>"+date[x]+"</td>");
                  document.write("<td>"+firstName[x]+" "+lastName[x]+"</td>");
                  document.write("<td>"+street[x]+"<br>"+city[x]+","+state[x]+" "+zip[x]);
                  document.write("<td class='amt'>$"+amount[x]+"</td>");
                  document.write("</tr)");
             }

         </script>
     </table>
    </body>
    </html>

**arrays.js**

street = new Array();
city = new Array();
state= new Array();
zip = new Array();
amount = new Array();
date = new Array();


firstName[0]="Ron";
lastName[0]="Burgundy";
street[0]="88 Regal Lane";
city[0]="Williamsburg";
state[0]="KY";
zip[0]="40769";
amount[0]=625;
date[0]="2015-07-18";


firstName[1]="Ricky";
lastName[1]="Bobby";
street[1]="407 Easy Street";
city[1]="London";
state[1]="KY";
zip[1]="40744";
amount[1]=75;
date[1]="2015-07-18";


firstName[2]="Veronica";
lastName[2]="Corningstone";
street[2]="743 Stawlings Drive";
city[2]="Danville";
state[2]="KY";
zip[2]="40423";
amount[2]=50;
date[2]="2015-07-16";


firstName[3]="Brick";
lastName[3]="Tamland";
street[3]="102 Maple Lane";
city[3]="Danville";
state[3]="KY";
zip[3]="40423";
amount[3]=150;
date[3]="2015-07-15";

Answer №1

1) Make sure to define the firstName and lastName variables in the arrays.js file. 2) Ensure that the tr tag is appropriately closed within the for-loop by changing document.write("</tr)"); to document.write("</tr>");.

Here is the corrected code:

Html Code:

` Winch - Lab 10 function totalContributions() { var totalAmount = 0; for (var i = 0; i < amount.length; i++) totalAmount = totalAmount + amount[i]; return totalAmount; }


    </script>
</head>
<body>
 <table id="donations" style="width:100%;" border="1">
     <tr>
         <th>Date</th>
         <th>Name</th>
         <th>Address</th>
         <th>Amount</th>
     </tr>
     <script>
         for (var x=0; x < amount.length; x++){
             if (x%2==0){
                document.write("<tr>");
             } else {
                 document.write("<tr class='stripe'>");
             }
              document.write("<td>"+date[x]+"</td>");
              document.write("<td>"+firstName[x]+" "+lastName[x]+"</td>");
              document.write("<td>"+street[x]+"<br>"+city[x]+","+state[x]+" "+zip[x]);
              document.write("<td class='amt'>$"+amount[x]+"</td>");
              document.write("</tr>");
         }

     </script>
 </table>
</body>
</html>

arrays.js

street = new Array();
city = new Array();
state= new Array();
zip = new Array();
amount = new Array();
date = new Array();
firstName = new Array();
lastName = new Array();

firstName[0]="Ron";
lastName[0]="Burgundy";
street[0]="88 Regal Lane";
city[0]="Williamsburg";
state[0]="KY";
zip[0]="40769";
amount[0]=625;
date[0]="2015-07-18";

firstName[1]="Ricky";
lastName[1]="Bobby";
street[1]="407 Easy Street";
city[1]="London";
state[1]="KY";
zip[1]="40744";
amount[1]=75;
date[1]="2015-07-18";

firstName[2]="Veronica";
lastName[2]="Corningstone";
street[2]="743 Stawlings Drive";
city[2]="Danville";
state[2]="KY";
zip[2]="40423";
amount[2]=50;
date[2]="2015-07-16";

firstName[3]="Brick";
lastName[3]="Tamland";
street[3]="102 Maple Lane";
city[3]="Danville";
state[3]="KY";
zip[3]="40423";
amount[3]=150;
date[3]="2015-07-15";

Answer №2

It's clear that the trend is towards Angular, so my recommendation would be to jump on board as well.

When it comes to utilizing Angular, you have a choice between using either the angular-data-table or the angular-material-data-table.

  • The angular-data-table functions perfectly with 1.5.8 but won't be supported in Angular2
  • The angular material-data-table (md-data-table) works seamlessly with 1.5.8 and will also be compatible with Angular2.

Here's an example of md-data-table:

<mdt-table table-card="{visible: true, title: 'Donations'}" paginated-rows = "true">
    <mdt-header-row>
      <mdt-column align-rule="left"><b>Name</b></mdt-column>
      <mdt-column align-rule="left"><b>Description</b></mdt-column>
      <mdt-column align-rule="left"><b>Since Year</b></mdt-column>
    </mdt-header-row>
    <mdt-row ng-repeat="item in donations">
      <mdt-cell>{{item.name}}</mdt-cell>
      <mdt-cell>{{item.description}}</mdt-cell>
      <mdt-cell>{{item.since_yr}}</mdt-cell>
    </mdt-row>
  </mdt-table>
  • This code snippet includes built-in pagination functionality. How convenient!
  • You can also enable row selection by adding:

    selectable-rows="true" inside the code

Here's what you need to do:

Create an Angular module using ng-app and include it in your body tag or wrap it in a parent tag above the code snippet. Create a controller to handle the logic. Here's an example:

angular.module('testModule',[])
        .controller('testController', function($scope){
            $scope.donations = function (){
                //Your donation logic belongs here.
            };      
        });

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

When a div is covered by an if statement

One of the challenges I am facing is managing a view with multiple projects, some of which are active while others are not. In my function, if a project's deadline has passed, it displays '0' days left on the view, indicating that these are ...

Troubleshooting Uploadify Issues

UPDATE: I discovered that the problem was related to Uploadify not having a session, which prevented it from accessing the designated page. To avoid this issue, simply direct it to a page without any admin login security ;) The issue stemmed from Upload ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

form controls disappear upon adding form tags

Currently experiencing an issue with angular and forms that I could use some help with. I have a dynamic form that is functioning properly, but now I need to add validations to it. After following this guide, I established the structure correctly. Howeve ...

Retrieve data from dropdown menu to showcase table using Node.js

I'm currently diving into learning nodejs and mongodb. My backend setup includes expressjs and mongojs, while ejs is handling the frontend of my application. The main goal is to allow users to select a class from a dropdown menu and view a correspondi ...

The material UI Paper component appears to be extending beyond the boundaries of the background image

I have configured the Grid component to occupy 6 on small/medium screens for a side-by-side layout and 12 on xs screens for each item. While everything looks fine in the computer view, I am facing an issue with the mobile view where the paper component is ...

After an AJAX request is completed, the event.keyCode is not returning the key codes for the up and

I have a function that uses AJAX to autocomplete a text field. The results are added to a specific div element. I am trying to implement the functionality where users can navigate through the results using the up and down arrow keys. However, I am encoun ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

Discovering common time intervals without the date component in between

I need to identify the intersection between two time ranges, focusing solely on the time and not the date. For instance, range_1 is from 9AM to 6PM while range_2 spans from 5PM to 8AM. The times are in the 24-hour format. I have a solution that finds the o ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

Can you provide instructions on integrating bootstrap 5.02 using npm and webpack?

Trying to bundle my webapp with webpack, but struggling with importing the bootstrap code. I've already spent hours troubleshooting this. Ever since setting up webpack, things haven't been working as they did before. And now, I keep encountering ...

Retrieve a data value from a JSON object by checking if the ID exists within a nested object

I am facing the challenge of navigating through a JSON object where child objects contain IDs that need to be matched with parent properties. The JSON structure looks like this: { id: 1, map: "test", parameter_definitions: [{ID: 1, pa ...

jquery mobile popup message will fade away within a short time interval

In my main page, I have the following code: $(document).bind("pageinit", function () { $.mobile.loading('hide'); }); I am displaying a popup message using the following code: $.mobile.loading('show&apos ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Update an array while monitoring for a specific event

Working with Ionic, my goal is to push an array of an object when a specific event is emitted. This is what I currently have: export class PublicationService { constructor(private storage: Storage) {} private addPublicationSubject = new Be ...

"Utilize JavaScript for graceful error handling in your project with

I am trying to implement an Ant task that involves adding JavaScript code. I want the success or failure of the target to be determined by the results of some logic executed in the JavaScript: <target name="analyze"> <script language="javas ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...