its not really a problem at the moment , its just that im after another solution. Surely there must be a smarter way for me then to write every student with an if questions as I have done here to get their grades.
If I want to get the same result but with a for loop? how would I go on doing that? any smart suggestions?
var nameandgrades = {
"students": [{
"namn": "Klara",
"grade": "A"
},
{
"namn": "Andrea",
"grade": "B"
},
{
"namn": "Emil",
"grade": "C"
}
]
};
var klara = "Klara";
var andrea = "Andrea";
var emil = "Emil";
function getGrade() {
var studentname = document.getElementById("studentname").value;
if (studentname == klara) {
document.getElementById("output").innerHTML = nameandgrades.students[0].grade + ' ';
}
if (studentname == andrea) {
document.getElementById("output").innerHTML = nameandgrades.students[1].grade + ' ';
}
if (studentname == emil) {
document.getElementById("output").innerHTML = nameandgrades.students[1].grade + ' ';
}
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title>json javascript</title>
</head>
<body>
<h1> Write the students name and see what grade he/she has! </h1>
<form>
<!-- textbox -->
<input type="text" id="studentname" value="Klara" placeholder="name of the student" />
<br />
<br>
<!-- mouseclick -->
<input type="button" value="visa" onclick="getGrade();" />
<br />
<br>
</form>
<div id="output"> </div>
</body>
</html>
Any help is much appreciated!
Cheers! //macgajver