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> </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> </label>
<input type="button" id="clear_button" value="Clear Student Scores" /><br />
<label> </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.