A JavaScript array that is appearing as "undefined" when displayed in a

I am currently working on a homework assignment and running into an issue where my array is showing up as undefined. I'm new to this, so forgive me if it's a simple mistake. Allow me to explain what I'm trying to accomplish here.

There are three input fields where I collect the last name, first name, and grade of a student. I gather these elements by their IDs and then populate an array called "studentGrade" with those inputs. Next, I push the contents of "studentGrade" into another array named "grades" to pass it as a parameter to a function called "get_item_list." The objective is to loop through the parameter content and display it in the text field identified as "scores."

I truly appreciate any guidance and hope that I can identify where I am going wrong.

var grades = [];

var $ = function (id) { return document.getElementById(id); }

var update_display = function () {
    $("scores").value = get_item_list(grades);

    $("last_name").value = "";
    $("first_name").value = "";
    $("score").value = "";

$("last_name").focus();
}    

var student_grade_add_click = function() {
    var studentGrade = [];
    studentGrade["last_name"] = $("last_name").value;
    studentGrade["first_name"] = $("first_name").value;
    studentGrade["score"] = parseFloat($("score").value);

    if ( studentGrade["last_name"] == "" ) return;
    if ( studentGrade["last_name"] == "" ) return;
    if ( isNaN(studentGrade["score"]) ) return;

    grades.push(studentGrade);
    update_display();
}

var get_item_list = function(item_list) {
    if ( item_list.length == 0 ) {
       return "";
    }
    var list;
    for ( var i in item_list ) {
        list += item_list[i] + "\n";
    }
    return list;
}

window.onload = function () {
    $("add_button").onclick = student_grade_add_click;
    $("last_name").focus();
}

This is the JavaScript code I am working with.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Student Scores</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript" src="student_scores.js"></script>
</head>

<body>
<div id="content">
    <h1>Student Scores</h1>
    <div class="formLayout">
        <label>Last Name:</label>
        <input type="text" id="last_name" /><br />

        <label>First Name:</label>
        <input type="text" id="first_name" /><br />

        <label>Score:</label>
        <input type="text" id="score" /><br />

        <label>&nbsp;</label>
        <input type="button" id="add_button" value="Add Student Score" /><br />
     </div>
    <h2>Student Scores</h2>
    <p><textarea id="scores" rows="5" cols="60"></textarea></p>
     <div class="formLayout">
        <label>Average score:</label>
        <input type="text" id="average_score"/><br />

        <label>&nbsp;</label>
        <input type="button" id="clear_button" value="Clear Student Scores" /><br />

        <label>&nbsp;</label>
        <input type="button" id="sort_button" value="Sort By Last Name" /><br />
    </div>
</body>
</html>

Here is the HTML structure I have created. Thank you once again for your help.

Answer №1

To properly concatenate values to the list variable, make sure to initialize it as a string beforehand:

var get_item_list = function(item_list) {
    if ( item_list.length == 0 ) {
       return "";
    }
    var list = "";
    for ( var i = 0; i < item_list.length; i++) {
       var current = item_list[i];
       for ( var attr in current ) {
           list += current[attr] + "\n";
       }
    }
    return list;
}

Additionally, note that studentGrade is an object, not an array, despite how keys are being set:

var studentGrade = {};

The updated changes have been successfully implemented. Click here to view the revised fiddle: http://jsfiddle.net/LFhNQ/1/

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

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

Replace all occurrences of "KEY" with "VALUE" using preg_replace in PHP

My current array is: $array = array( '/news/show/([0-9])/([0-9])'=>'/news/show/id/$1/id2/$2', '/home/ayz/([0-9])'=>'/home/xyz/sid/$1' ); I am aiming for the following result: $array = array( ' ...

Retrieve the selected options from the checkbox and transfer them to the input text field

In the following example, I am attempting to extract all values of the inputs once they are checked and display them in a text input that will be sent via email. However, I am facing an issue where only the last option is being printed in that input instea ...

Using React Native to share API and passing a Base64 string in place of an image when sharing to WhatsApp

I am facing difficulties in sharing a base64 image on WhatsApp. On both iOS and Android, the actual base 64 code is shared instead of the image. When I try to use iMessage or Email on iOS, the base64 images are converted and displayed correctly. However, ...

Modify the PrimeFaces dialog to be modal using client-side code

One of my primefaces dialogs is set up like this: <p:dialog widgetVar="dlg" width="320" height="220" modal="false" closable="false" showHeader="false" resizable="false" position="right,top"> I am looking to make this dialog modal if a certain eleme ...

Click on a plane within a three.js environment to determine the X Y position within it

When using a raycaster, I can successfully obtain the current object (in this case, a plane) under the mouse. However, I am seeking a more precise X and Y value for the mouse position INSIDE the plane. var vector = new THREE.Vector3( ( event.clientX / win ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

JavaScript nested arrays not functioning with .map()

I've encountered a problem while using the .map function in JavaScript to extract a nested array from an API response. Here is the JSON: [ { "id": 3787, "title": "Dummy title!", "start_time": "2020-04-25T16:54:00.000Z", ...

Converting PHP columns into rows within arrays

Currently, I have reached this section of the script: dif($result>0) { $ii=0; $jj=0; while (odbc_fetch_row($result)) { for ($jj = 1; $jj <= odbc_num_fields($result); $jj++) { $rr[$ii][$jj]=odbc_result ...

Developing a fresh feature in Angular.js for transmitting my localstorage model information to a bus?

As a beginner in Angular Js, I have mastered the basics and am now working on storing user input values to localstorage using a form. Although this part is working fine, I need assistance in creating a new service to communicate with my colleague's . ...

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Do not allow navigation to another page until the form has been submitted

As part of my project, I have implemented a feature where new users are required to change their password upon logging into their account for the first time. For new users, the Change Password screen is displayed immediately after login. The menu options ...

The efficiency of a for loop in Javascript can be influenced by the way the loop

I experimented with three different for loop cases in JavaScript, each performing a seemingly useless action 1000000000 times. Surprisingly, the speed of these codes varied from one another. Initially, I suspected that the difference in performance could ...

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Creating an external JavaScript and CSS file for date picker in Eclipse can be done by following a few simple steps. By creating separate files for the

I am using the following javascript and css styles: <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jq ...

"Can you tell me more about the purpose of $cacheFactory

I am struggling to find information on the purpose and functionality of $cacheFactory in application development. According to the Angular Documentation, "Factory that constructs cache objects and gives access to them." -- $cacheFactory However, this e ...

What is the process for dynamically looping through a table and adding form data to the table?

I am in the process of developing an hour tracking website that utilizes a form and a table. Currently, I have implemented the functionality where the form content gets added to the table upon the first submission. However, I need it to allow users to inp ...

What is the best way to retrieve the post JSON data in the event of a 404 error?

When my service call returns a 404 error, I want to display the server's message indicating the status. The response includes a status code and message in JSON format for success or failure. This is an example of my current service call: this._trans ...