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

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();
  }
}