Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Search results shows info for every student searched for, does not clear and only show last student searched for.

I'd like to only show the most recent student searched for, but each time I search for a new student, it adds their info to the bottom of the last students info.

here is my code:

var html = ""; var name = ""; function ask() { name = prompt("Please input name of student whose records are desired. If you are done searching, type 'exit'") };

function print(message) { var outputDiv = document.getElementById('output'); outputDiv.innerHTML = message; }

ask(); for (i=0; i<students.length; i++) { if (name.toLowerCase() === "exit") { break; } else if (name.toLowerCase() === students[i]['name'].toLowerCase()) { for (prop in students[i]) { html += "<p>" + prop + ": " + students[i][prop] + "<p>"; } print(html); ask();

} }

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hey Bryan,

This is because you are not resetting the 'html' variable after each search. So this variable still contains all of the previous information.

Add 'html = "";' into your code:

ask();
for (i=0; i<students.length; i++) {
  if (name.toLowerCase() === "exit") {
    break;
  } else if (name.toLowerCase() === students[i]['name'].toLowerCase()) {
    html = ""; // <-- here :)
    for (prop in students[i]) {
      html += "<p>" + prop + ": " + students[i][prop] + "<p>";
    }
    print(html);
    ask();
  }
}