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

Trouble with installing Enmap due to better-sqlite3 error

For a while now, I've been struggling to get enmap installed. Despite searching the web exhaustively, I haven't come across any solutions that work for me. Every time I try npm i enmap, I consistently encounter this frustrating error: One part o ...

Is it better to specify one root element or render the entire layout in ReactDOM.render()?

Currently in the process of learning React.js and I have a question. Is it more beneficial to keep my ReactDOM.render() as it is currently set up: ReactDOM.render( <div className="container"> <div className="row"> <div className ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Using placeholders with inputs in an Angular2 table generated by ngFor

I have an array public example = [['hallo', 'fruit', 'rose'], ['apple','book']] Currently, I am working on creating a table of inputs. The values in this table depend on the specific part that I am usin ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $req ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

Retrieve the value from an input field when the value is returned from JavaScript

Scenario: I'm currently working on creating a QR reader to retrieve a specific value. You can check out the progress here: What's functioning: scanning. When I scan a QR code, a value is displayed in the text box. Here's the code snippet b ...

The appearance of the pop-up mask is displayed at lightning speed

Check out the demo here Here is the HTML code: <div class="x"> </div> <input class="clickMe" type="button" value="ClickMe"></input> This is the JS code: $(".clickMe").click( function() { ...

audio enhancement in a web-based game

I'm having trouble getting a sound effect to play consistently in my game whenever there is a hit. Sometimes the sound plays, other times it does not! Here is the code I am using: <script> var hitSound = new Audio(); function playEffectSound ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

I am attempting to achieve a smooth transition effect by fading in and out the CSS background color using JQuery and AJAX

Can anyone help me with my issue related to using Ajax to fadeIn a background color in beforeSend and fadeOut in success? I seem to have made some mistakes but can't figure out what went wrong. var data={ ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Tips for eliminating the left and bottom border in a React chart using Chart.js 2

Is there a way to eliminate the left and bottom borders as shown in the image? ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

What is the best way to clear the content of a contenteditable element in React?

I have a scenario where I am rendering an array of items, each with a contenteditable field. MainComponent.js import { useState } from "react"; import Item from "./Item"; import "./styles.css"; export default function MainC ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...