lefty lefty - 18 days ago 8
JSON Question

How to loop through a Json objects based on an input from the user and then use the object properties?

I am new to JavaScript and I'm trying to make a website where a student types in his student id, and the website will show which exercises he has handed in. I can loop through all the students and check if they have handed in an exercise, but I want to know how to check if the input value, matches with one of the students ids, then show which exercises that one person has completed.

Here is a pen code of my current code:
http://codepen.io/lefty11/pen/aBdXJo

var students = [
{"Name":"John","Last_Name":"Bazel","StudentId":"s123456","HandIn1":"ok","HandIn2":"not ok","HandIn3":"ok"},
{"Name":"Sara","Last_Name":"Black","StudentId":"s123457","HandIn1":"not ok","HandIn2":"ok","HandIn3":"ok"},
{"Name":"Alex","Last_Name":"Semar","StudentId":"s123458","HandIn1":"ok","HandIn2":"ok","HandIn3":"not ok"}
];

function getStudent(){
var inputValue = document.getElementById("user_input").value;
if(students.StudentId == inputValue){
checkOblig();
}
}
function checkOblig(){
var i;
for(i = 0; i < students.length; i++){
if(students[i].HandIn1 == "ok"){
document.write(" Oblig1 Completed ");
}
}
}
checkOblig();


-

<form>
<label><b>Enter Your Student Id</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" id="sumbit" value="Submit">

Answer

You first need to iterate over each student to find the one with the entered ID.

When you found it you can check his exercises status

var students = [{
  "Name": "John",
  "Last_Name": "Bazel",
  "StudentId": "s123456",
  "HandIn1": "ok",
  "HandIn2": "not ok",
  "HandIn3": "ok"
}, {
  "Name": "Sara",
  "Last_Name": "Black",
  "StudentId": "s123457",
  "HandIn1": "not ok",
  "HandIn2": "ok",
  "HandIn3": "ok"
}, {
  "Name": "Alex",
  "Last_Name": "Semar",
  "StudentId": "s123458",
  "HandIn1": "ok",
  "HandIn2": "ok",
  "HandIn3": "not ok"
}];

function checkOblig() {
  var inputValue = document.getElementById("user_input").value.trim();
  if (inputValue === "")
    alert("Please enter your ID");

  let student = null;
  for (let i = 0; i < students.length; i++) {
    let student = students[i];
    if (student.StudentId === inputValue) {
      //student found
      if (student.HandIn1 === "ok") {
        console.log("Oblig1 completed");
      } else {
        console.log("Oblig1 not completed");
      }
      if (student.HandIn2 === "ok") {
        console.log("Oblig2 completed");
      } else {
        console.log("Oblig2 not completed");
      }
      if (student.HandIn3 === "ok") {
        console.log("Oblig3 completed");
      } else {
        console.log("Oblig3 not completed");
      }
    }
  }
}
<form>
  <label><b>Enter Your Student Id</b>
  </label>
  <input type="text" name="message" id="user_input">
</form>
<input type="submit" id="sumbit" value="Submit" onclick="checkOblig()">

Comments