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

Kyle Jensen
PLUS
Kyle Jensen
Courses Plus Student 6,293 Points

Optional solution to Student Search Challenge, with additional changes to input.

Here is my solution to the challenge. It uses a text box rather than the window prompt. Let me know what you think.

//did not write this print function(owned by Dave McFarland - Treehouse)
function print(message) { 
  var outputDiv = document.getElementById('records');
  outputDiv.innerHTML = message;
}

var students = [
    { name: 'Chris', track: 'Full-stack developer', achievements: 50, points: 16280 },
    { name: 'Dave', track: 'Engineer', achievements: 75, points: 18722 },
    { name: 'Danny', track: 'Software QA', achievements: 150, points: 42085 },
    { name: 'Chris', track: 'Artist', achievements: 40, points: 13670 },
    { name: 'Bob', track: 'Director of photography', achievements: 110, points: 27345 },
    { name: 'Chris', track: 'Unity Developer', achievements: 130, points: 28956 },
    { name: 'Dave', track: 'Machine Learning', achievements: 77, points: 20722 },
];

var button = document.querySelector('#submit');
button.addEventListener('click', function() {
    var input = document.getElementById('txtBox').value;
    var output = document.getElementById('records');
    var html = '';
    var prevName;
    for(var i = 0; i < students.length; i++) {
        var current = students[i];
        if(current.name === input ) {
            html += '<h2>Student: ' + current.name + '</h2>';
            html += '<p>Track: ' + current.track + '</p>';
            html += '<p>Achievements: ' + current.achievements + '</p>';
            html += '<p>Points: ' + current.points + '</p>';
            print(html);
            prevName = current.name;
            current = '';
        } 

        else if(i === students.length - 1 && prevName === undefined){
            output.style.color = 'red';
            html += '<h1>' + input + ' is not a student</h1>';
            print(html);
            break;   
        }
    }
});