Reputation: 435
Ok guys. Javascript newbie here. Basically, I need to write a basic quiz about music. I need the user to type in the answer they think, and at the end, it outputs the answer they wrote and tells them if its wrong/right. My logic, was this:
But the problem Im facing is the userAnswers array. Ive defined it empty but when the browser enters the for loop, it should populate it with the users answer but it doesn't since I try to print out the array at the end of the loop to see if it contains the users answer but it doesnt print....
my code:
<!DOCTYPE>
<html>
<head>
<title> Quiz </title>
</head>
<body>
<input type="button" value="Start the quiz" name="quiz" onclick="gettingAnswers();" />
<script>
var questions = ["How many times did 50 cent get shot?",
"What year did Micheal Jackson die?",
"How many awards has Drake recieved as of January 2015?",
"What year did Kanye West win his first award?"];
var userAnswers = [];
function gettingAnswers ()
{
for(var i = 0; i < questions.length; i++)
{
var answers = prompt(questions[i]);
userAnswers[i] = answers;
}
}
document.write(userAnswers);
</script>
</body>
</html>
(excuse the questions, couldn't think of anything else....)
Upvotes: 1
Views: 35
Reputation: 64657
First off, you should move the write to the end of the function:
function gettingAnswers (){
for(var i = 0; i < questions.length; i++){
var answers = prompt(questions[i]);
userAnswers[i] = answers;
document.write(userAnswers);
}
userAnswers
is an array, not a string. You probably want to change it to something like:
document.write(userAnswers.join("<br>"));
which would output each answer, seperated by an html line break.
Upvotes: 1
Reputation: 3570
Move "document.write(userAnswers);" inside the function. I checked and it works.
function gettingAnswers () {
for(var i = 0; i < questions.length; i++){
var answers = prompt(questions[i]);
userAnswers[i] = answers;
}
document.write(userAnswers);
}
Upvotes: 0