Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Inês Lamares
Inês Lamares
2,079 Points

The alert box only pops-up, if I introduce a name that doesn't exist the first time the prompt box appears, why?

Here is the code, hope some one can help me, thanks! https://w.trhou.se/48xgx9ug8s

1 Answer

Simon Coates
Simon Coates
28,694 Points

maybe try resetting the student count each time through the loop. eg.

while(true){
  search = prompt( "To search for a student record please insert the name or quit to exit." );
  noStudent= 0;
Simon Coates
Simon Coates
28,694 Points

I'm not very good at javascript, but you could replace the count with a boolean, count the matching records (print not found if matchingrecords === 0), or use students.length instead of 5. I would have tried something like:

var student;
var search = ""; 

function print (message){
  var div = document.getElementById("output");
  div.innerHTML += message;
}

while(true){
  search = prompt( "To search for a student record please insert the name or quit to exit." );
  if (search === null || search.toLowerCase() === "quit") {
    break;
  }
  var found = false;
  for( i = 0; i < students.length; i += 1 ){
    student = students[i];
    if (search.toLowerCase() === student.name.toLowerCase()) {
      found = true;
      var message = "<h2>Name: " + student.name + "</h2>";
      message += "<p>Track: " + student.track + "</p>";
      message += "<p>Achievements: " + student.achivements + "</p>";
      message += "<p>Points: " + student.points + "</p>";
      print (message);      
    }
  }
  if (!found){
     alert (" The student name you entered doesn't exist.");
  }
}

nb: this also alters print, so that it appends to the div, rather than storing the complete message.

Inês Lamares
Inês Lamares
2,079 Points

Hi Simon, Thanks so much! So obvious and I couldn't see it. Both work, but the 2nd option it's better. thanks again!