JavaScript Practice: Student Record Search

by Melinda Golden

HTML

<div id="output"></div>

JavaScript

// Declare variables
var message = "";
var search;

// Create students array containing objects
var students = [
	{
  	name : "Melinda",
    track : "Front End Development",
    achievements : 30,
    points : 7000
  },
  {
  	name : "Chris",
    track : "Web Design",
    achievements : 20,
    points : 5000
  },
  {
  	name : "April",
    track : "PHP Development",
    achievements : 40,
    points : 3000
  },
  {
  	name : "Taylor",
    track : "JavaScript Development",
    achievements : 10,
    points : 2000
  },
  {
  	name : "James",
    track : "iOS",
    achievements : 5,
    points : 1000
  }
];

// Displays a message to the page
function print(message) {
	var div = document.getElementById('output');
  div.innerHTML = message;
}

/*
	1. Prompt user for name and store in search variable
  2. If the user enters 'quit' then end the loop
  3. Otherwise, create a loop that interates through the students array.
  4. If the search is the same as the value of the name property, then display the properties and values of that object
  5. End the loop
*/
while (true) {
	search = prompt("Search the student records. Type a name (or type quit to end)");
  if (search === null || search.toLowerCase() === 'quit') {
  	break;
  } else {
  	for (var i = 0; i < students.length; i++) {
      if (search === students[i].name) {
        var prop = students[i];
        message += "<p><strong>Student: " + prop.name + "</strong></p>";
        message += "<p>Track: " + prop.track + "</p>";
        message += "<p>Achievements: " + prop.achievements + "</p>";
        message += "<p>Points: " + prop.points + "</p>";
        
      }
    }
    break;
  }
}

// Displays the object on the page
print(message);