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

My solution for search challenge

1 Answer

I made a couple changes.

var message = '';
var student;
var searchField;

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

function getStudent(studente) {
  var record = '';
  if (studente.length > 0 ){
    for (var i = 0 ; i < studente.length ; i += 1) {
      student = studente[i];
        record += '<h2>Student: ' + student.name + '</h2>';
        record += '<p>Track: ' + student.track + '</p>';
        record += '<p>Points: ' + student.points + '</p>';
        record += '<p>Achievements: ' + student.achievements + '</p>';
    }
  } else {
    record += 'Mi dispiace non abbiamo studenti che si chiamano ' + searchField;
  }
  //console.log(record);
  print(record);
}

function chi(nome) {
  var risultati = [];
  for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (student.name.toLowerCase() === nome.toLowerCase()) {
      risultati.push(student);
    }
    //getStudent(risultati); //changed this
  }
  getStudent(risultati); //moved this
}

do {
  searchField = prompt('Inserisci un nome o digita "quit" per interrompere');
  chi(searchField);
} while (searchField.toLowerCase() !== 'quit' )

You were calling getStudent(risultati); repeatedly, as it was inside a loop. It was overwriting outputDiv.innerHTML again and again. Apart from this, I came up with the same solution.

The print method is concealing the flaw (it replaces content, rather than just adding). You can see the problem if you replace print with:

function print(message) {
 document.write( message);
}