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 trialJoram Livengood
Full Stack JavaScript Techdegree Student 14,603 PointsNew print function is not working with my code
I wrote all of the code during the challenge for the first video, and I got everything to work.
However, I started watching this video and I changed my print function from the document.write method to this innerHtml method, and now it's not printing MOST of my code!
Can anyone see why this might be happening? (note: this code is sloppy)
var questionsList = [ ["What is 2 + 2?", "4"], ["What color is Darci?", "black"], ["What color is Penny?", "brown"] ] var correctScore = 0; var wrongScore = 0; var askQuestion;
function print(message) { var outputDiv = document.getElementById("output"); outputDiv.innerHTML = message; }
function printScore() { var correctHeadline = "<p>You got ";
var correctList = "<h2>You got these questions correct:</h2> <ol>"; var wrongList = "<h2>You got these questions wrong:</h2> <ol>";
for (i = 0; i < questionsList.length; i++) { askQuestion = prompt(questionsList[i][0]); askQuestion = askQuestion.toLowerCase(); if (askQuestion === questionsList[i][1]) { correctScore += 1; correctList += "<li>" + questionsList[i][0] + "</li>"; } else { wrongScore += 1; wrongList += "<li>" + questionsList[i][0] + "</li>"; } }
if (correctScore === 0) { correctHeadline = "<p>You should try again.</p>"; correctList = ""; } else { correctHeadline += correctScore + " of the questions right!</p>"; correctList += "</ol>"; }
if (wrongScore === 0) { correctHeadline = "<p>YOU GOT ALL THE QUESTIONS RIGHT!</P>"; wrongList = ""; } else { wrongList += "</ol>"; }
print(correctHeadline); print(correctList); print(wrongList); }
printScore();
1 Answer
Steven Parker
231,236 PointsThe assignment in your "print" function replaces the contents of the "outputDiv" each time you call it.
If you want to accumulate instead of replace, use the addition assignment operator instead:
outputDiv.innerHTML += message;
Joram Livengood
Full Stack JavaScript Techdegree Student 14,603 PointsJoram Livengood
Full Stack JavaScript Techdegree Student 14,603 PointsDuh! One little thing. Thanks!!!
Steven Parker
231,236 PointsSteven Parker
231,236 Pointsc'est la codage!