I've made a JS/HTML quiz, and I want all the words entered in the text fields to be displayed at the bottom of the page on submission.
The error is in the showResults function, which isn't working the way I intend it to. I'm a beginner at using the querySelector but what I want to do is use the variable answerContainers to store only the .answers part of quizContainer, and then the toSearch variable to store only the values of submitted answers from answerContainers. Finally, I want to print the contents of toSearch to the screen in string form.
Here's my code:
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
var myQuestions = ["1. What is your dream destination?",
"2. If you could have one wish right now, what would it be?",
"3. What are your career goals?",
"4. Name an artist whose music you enjoy.",
"5. What are your hobbies?",
"6. Name a few public figures you admire.",
"7. Who is your favourite actor?",
"8. Which family member do you love the most?",
"9. If you could have any animal as your pet, what would it be?",
"10. Name a movie you’ve been planning to watch but haven’t yet had the time.",
"11. What kind of weather do you like the most?",
"12. Name a book or movie that you’ve always loved."];
function showQuestions(myQuestions, quizContainer){
var output = [];
for(var j = 0; j <= 11; j++)
{
var answer = '<label>'
+ '<input type="text" name=""+j+"" id=""+j+"">'
+ '</label>';
output.push(
'<div class="question">' + myQuestions[j] +'</div>'
+ '<div class="answers">' + answer + '</div>'
);
}
quizContainer.innerHTML = output.join("");
}
function showResults(questions, quizContainer, resultsContainer){
var answerContainers = quizContainer.querySelectorAll('.answers');
var toSearch = [];
for(var i=0; i <= 11; i++){
toSearch.push(answerContainers[i].querySelector('input[name=""+i+""]')).value;
}
resultsContainer.innerHTML = toSearch.toString();
}
<!DOCTYPE html>
<html>
<head>
<h2>Interests Questionnaire</h2>
<h4>Answer in 1-5 words each.</h4>
<br>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div id="quiz"></div>
<div id="results"></div>
<script src = "test.js"></script>
<script> showQuestions(myQuestions, quizContainer); </script>
<input type="button" value = "Submit" id = "submit" onclick = "showResults(myQuestions, quizContainer, resultsContainer)">
</body>
</html>
In its current form, the code gives the error "JavaScript error: TypeError: quizContainer is null on line 52". What am I doing wrong and how can I fix it?