I am confused about what my teacher wants me to do. Have I interpreted the task correctly?

I completed the assignment, but I'm still unclear if I have fully grasped my teacher's instructions. Can you provide some insight on this for me?

I attempted to solve it using two arrays, a for-loop, and connecting a button with a function, and it seems to be working. However, the question remains - is it correct? Since my school assignment is in Swedish, some words may be in that language.

Here is the assignment question:

Morgan, a high school teacher, needs a register to keep track of their students' grades. You are given two arrays, one containing names and the other containing grades. For example: name = ["Klara", "Andrea", "Emil", "Sarah", "Alicia", "Victor", "Thomas", "Robert"] with grades: grade = ["A", "B", "C", "A", "D", "C", "E", "E"]. Your task is to create a function (getGrade) that searches for a name and returns the corresponding grade. Then, create a page to test and demonstrate your new feature (either automatically when the page loads or via a button press). The arrays can either be global variables or preferably local variables passed as input to functions.

<body>

  <input type="button" value="Click to get Student Name and Grade" onclick="getGrade()">
  <div id="student1"></div>
  <div id="student2"></div>
  <div id="student3"></div>
  <div id="student4"></div>
  <div id="student5"></div>
  <div id="student6"></div>
  <div id="student7"></div>
  <div id="student8"></div>


  <script>
    var name = ["Klara", "Andrea", "Emil", "Sarah", "Alicia", "Victor", "Thomas", "Robert"];

    var grade = ["A", "B", "C", "A", "D", "C", "E", "E"];

    function getGrade() {

      for (var i = 0; i < name.length; i++) {
        if (name[i] == name[0]) {
          document.getElementById("student1").innerHTML += name[i] + "<br/> Grade: " + grade[i];
        } else if (name[i] == name[1]) {
          document.getElementById("student2").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else if (name[i] == name[2]) {
          document.getElementById("student3").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else if (name[i] == name[3]) {
          document.getElementById("student4").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else if (name[i] == name[4]) {
          document.getElementById("student5").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else if (name[i] == name[5]) {
          document.getElementById("student6").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else if (name[i] == name[6]) {
          document.getElementById("student7").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        } else {
          document.getElementById("student8").innerHTML += name[i] + "<br/> Grade: " + grade[i];;
        }

      }
    }
  </script>

Thank you for your feedback!

Answer №1

For this task, you need to obtain the grade of a student named X.

The function getGrade is responsible for fetching the grade of student X.

Student X can be specified through an input text or any other means.

In addition, the getGrade function should be able to accept a parameter.

To put it simply,

var grade = getGrade('Klara');

function getGrade(name) {
   var grade = ...
   return grade;
}

Answer №2

I found the question confusing as it was provided in two separate arrays. I am not sure about the tools that can be used for this assignment, but essentially you would need something similar to this:

var names = ['Klara', 'Andrea', 'Emil', 'Sarah', 'Alicia', 'Victor', 'Thomas', 'Robert'];

var grades = ['A', 'B', 'C', 'A', 'D', 'C', 'E', 'E'];
var dictionary = {};
for (var i = 0; i < names.length; i++) {
  dictionary[names[i].toLowerCase()] = grades[i];
}

function getStudentGrade(name) {
  return dictionary[name.toLowerCase()] || undefined;
}
var $app = document.body;
var input = document.createElement('input');
input.type = 'text';
var button = document.createElement('button');
var ul = document.createElement('ul');
button.innerText = 'Get Grade';
button.addEventListener('click', function() {
var grade = getStudentGrade(input.value)
  if (grade) {
    var li = document.createElement('li');
    li.innerText = input.value + ' grade is: ' + grade;
    ul.appendChild(li);
  }
});

$app.appendChild(input);
$app.appendChild(button);
var div = document.createElement('div');
div.appendChild(ul);
$app.appendChild(div);

I haven't made many refactors in terms of creating elements or other tasks;

If the student's grade corresponds directly to their position in the name array, you can create an Object with key value pairs and then retrieve the grade by passing the student's name.

I also added an input field to enter the student's name and generate the list by clicking on a button.

If you want to refactor your solution, you could consider something like this:

var names = ["Klara", "Andrea", "Emil", "Sarah", "Alicia", "Victor", "Thomas", "Robert"];

var grades = ["A", "B", "C", "A", "D", "C", "E", "E"];

function getGrade() {
    for (var i=1; i<=names.length; i++) {
      document.getElementById('student' + i ).innerText = names[i-1] + ' Betyg' + grades[i-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

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

When making an asynchronous call, only the initial character is shown in the (HTML) listbox elements

I have a query regarding AngularJS compatibility with IE9. My issue is with a modal window containing a patient list. <div class="modal-header"> <h3 class="modal-title">Patient list</h3> </div> <div class="m ...

NgModel in Angular Datapicker does not successfully transmit value

My page features a form that functions as a filter search, with one of the fields being a date field. I have configured the Angular UI datepicker plugin (https://github.com/angular-ui/ui-date) and the calendar pops up when I focus on the date field. Howe ...

Tips for implementing import or require in Electron

Currently, I am in the process of developing an electron app. I would like to incorporate some functions from other JS files into my project. However, when attempting to use the import statement, an error is triggered "cannot use import statement outside a ...

Using React - How to access prop values within child menus of Ant Design Dropdown

I have a feed of posts similar to a Facebook timeline, where each post has a dropdown menu with options for "edit, delete, report". Using the Ant Design UI library, I encountered an issue where I couldn't access the prop value "DeleteId" within the c ...

Include a script tag in a React component in NextJS without relying on props or context

Currently, I am trying to include a library in my React component using a script tag. My approach involves calling an API in an _app.tsx file and then accessing the result in a _document.tsx file. In the _document.tsx file, I add the script tag to the docu ...

AngularJS: accessing remote systems - a guide

I am looking to explain my objective clearly I need guidance on how to establish a remote desktop connection from my Angular.js application to a windows application running system. The server I am using is Google App Engine. My current ideas: The Windo ...

error: the program has encountered a segmentation fault and has created a core dump

Created a program to calculate the scalar product of two arrays following this formula: uv = u1v1 + u2v2 + u3v3 + ... un*vn Upon entering both arrays from the user, an error message "signal: segmentation fault (core dumped)" is displayed. Below is the c ...

Why is it that when I use require.js, all my modules appear to be loading at once when the page first

During the development of my single-page backbone app using requirejs, I encountered an issue when deploying to our beta server. The initial page load took around 20 seconds as it had to fetch all the necessary scripts. I initially believed that this dela ...

Tips for integrating AudioWorklets with vue-cli, webpack, and babel (resolved illegal invocation error)

I'm experiencing some challenges while attempting to develop a WebApp using vue-cli with AudioWorklets. Whenever I try to access properties of my AudioWorkletNode, such as port or channelCount, I encounter multiple errors: TypeError: Illegal invocati ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...

The lookat function in Three.js appears to be inverted

Here is a demonstration of my point: Check out the Test Site or (Backup link) I am facing an issue where, despite the correct mouse vector, my object always rotates by 90 degrees in favor of the positive Y axis. The problem seems to be related to the call ...

Transferring PHP Arrays to JavaScript with JQuery

I am facing an issue with redrawing markers (on Google Maps) from a database using jQuery form. Here is the code snippet: Index.html: var map; var data; function updateLocations(){ var post= $.post('php/getLoc.php',{table: "Auto"), functio ...

Activating the change event in jQuery: A step-by-step guide

Within my ASP.NET page, I have included a UserControl that contains a RadioButtonList. Whenever an item in the RadioButtonList is changed, I need to trigger the following jQuery function: $('#rdlUser').change(function (e) { alert("change fun ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

Deciphering JSON data in a textarea following a POST request

I am struggling with decoding a JSON string in PHP and I have identified the problem causing it. However, I am unsure of how to fix it. My approach involves putting an array that I convert to JSON into a hidden textarea, which I then post along with other ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Encountering a Javascript 404 error while attempting to make an API call

I encountered an issue while trying to modify data in my database. When my api request is made, I am receiving the following error: Uncaught (in promise) SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Additionally, I am r ...

Issues with jQuery .click and .html functions not functioning as expected

Does anyone have experience creating a game with jQuery? I can't seem to get the options after the first choice to work. Sorry, I don't have a working example at the moment. --- jQuery --- $(document).ready(function() { $(".console"). ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...