Ссылка на рабочий код
Только первые переключатели и последние регистрируются как правильные ответы. Я не уверен, в чем проблема с моим кодом.
В консоли отображаются следующие ошибки:
Uncaught TypeError: Невозможно прочитать свойство 'querySelector' из неопределенного в приложении. js: 94 Ошибка (L: 94) const userAnswer = (answerContainer .querySelector (селектор) || {}). value; в Array.forEach () в HTMLButtonElement.showResults (приложение. js: 89) Ошибка (L: 89) myQuestions.forEach ((currentQuestion, questionNumber) => {
Мне также трудно понять, как зарегистрировать мой ответ в виде текстового поля. Если кто-нибудь может помочь и направить меня в правильном направлении. Это будет с благодарностью. Спасибо
JavaScript
//Variables
//Saving HTML ID's as varibales for further use within JS.
const userName = document.getElementById('user-name');
const userBtn = document.getElementById('user-name-button');
const userNameSection = document.getElementById('get-user-name-section')
const quizContainer = document.getElementById('quiz-container');
const btnGroup = document.getElementById('button-group');
userBtn.addEventListener('click', getUserName);
function getUserName() {
if(userName.value.length === 0) {
alert("Please enter your name!")
} else {
alert("Welcome " + userName.value + ". Good Luck!");
userNameSection.style.display = 'none';
btnGroup.style.display = 'block';
quizContainer.style.display = "block"
}
}
function buildQuiz(){
const output = [];
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
if (currentQuestion.inputType === "radio") {
// answers in a radio style ...
// and for each available answer...
for (letter in currentQuestion.answers) {
// ...add an HTML radio button
// add this question and its answers to the output
answers.push(`<label><input type="radio" name="question${questionNumber}" value="${letter}">${letter} : ${currentQuestion.answers[letter]}</label>`);
}
// add this question and its answers to the output
//Q:${questionNumber + 1} - This is writting the question number to the screen. +1 is used because array index starts at 0 - This applies to all of the below conditionals
output.push(`<div class="slide"><div class="question"> Q:${questionNumber + 1} ${currentQuestion.question} </div><div class="answers"> ${answers.join("")} </div></div>`);
}
else if (currentQuestion.inputType === "checkbox") {
// answers in a checkbox style ...
for (letter in currentQuestion.answers) {
// ...add an HTML checbox button
answers.push(`<label><input type="checkbox" name="question${questionNumber}" value="${letter}">${letter} : ${currentQuestion.answers[letter]}</label>`);
}
// add this question and its answers to the output
output.push(`<div class="slide"><div class="question"> Q:${questionNumber + 1} ${currentQuestion.question} </div><div class="answers"> ${answers.join("")} </div></div>`);
}
else if (currentQuestion.inputType === "text") {
// answers in a text input style ...
for (letter in currentQuestion.answers) {
// add a HTML input text field
//Adding a span element to wrap around the text input. Can now select this element in CSS to display block so the input field will be on its own line and give give further styling
//The ${letter} literal has been moved from this in the value because the text box should be blank from the start
answers.push(`<span class="input-span"><label><input type="text" name="question${questionNumber}" : ${currentQuestion.answers[letter]}</label></span>`)
}
//Add this question and its answers to the output
output.push(`<div class="slide"><div class="question"> Q:${questionNumber + 1} ${currentQuestion.question} </div<div class="asnwers"> ${answers.join("")} </div></div>`)
}
}
);
// finally combine our output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join('');
};
function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
if (currentQuestion.inputType === "radio") {
// radio answer/response
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[questionNumber].style.color = 'lightgreen';
}
// if answer is wrong or blank
else {
// color the answers red
answerContainers[questionNumber].style.color = 'red';
}
}
else if (currentQuestion.inputType === "checkbox") {
// checkbox answer/response
// find selected answer
// **** IT IS CURRENTLY CHECK RADIO STYLE - this codepen.io is only a demonstration of how to detect various inputType ...
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[questionNumber].style.color = 'lightgreen';
}
// if answer is wrong or blank
else {
// color the answers red
answerContainers[questionNumber].style.color = 'red';
}
}
else if (currentQuestion.inputType === "text") {
// text input answer/response ...
if (currentQuestion.correctAnswer === "enterprise") {
numCorrect ++;
}
}
});
// show number of correct answers out of total
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
showAllSlides();
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.style.display = 'none';
} else {
previousButton.style.display = 'inline-block';
}
if (currentSlide === slides.length - 1) {
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
} else {
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
function showAllSlides() {
const slides = document.querySelectorAll(".slide");
slides.forEach(slide => {
slide.classList.remove("active-slide");
slide.classList.add("slide-show");
})
};
// Variables
//Const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [
{
//Question 1
question: "What is the name of Captain Sisko's son?",
answers: {
a: "Jake",
b: "Wesley",
c: "Myles"
},
correctAnswer: "a",
//The a new inputType element to the object - This will be used in the build quiz function and will determine which input type the question will be able answerd in -
//As example if the inputType is equal to radio, this means the question will be a multiple choice question with a radio button as the answer input type
//This rule applies to all questions
inputType: "radio"
},
{ //Question 2
question: "Finsish this quote.... 'Space, the final fronteir. These are the voyages of the starship......'",
answers: {
a: "",
// b: "",
// c: ""
},
correctAnswer: "enterprise",
inputType: "text"
},
{ //Question 3
question: "Who is the Captain of the USS Voyager?",
answers: {
a: "Captain Picard",
b: "Captain Janeway",
c: "Captain Kirk"
},
correctAnswer: "b",
inputType: "radio"
},
{ //Question 4
question: "What quadrant of space did the USS Voyger get lost in?",
answers: {
a: "Aplha Quadrant",
b: "Beta Quadrant",
c: "Delta Quadrant"
},
correctAnswer: "c",
inputType:"radio"
},
{ //Question 5
question: "Which flag belongs to the Romulan Empire?",
answers: {
a: "",
b: "",
c: ""
},
correctAnswer: "b",
inputType: "img"
},
{
//Question 6
question: "What planet is Quark, Rom and Nog from?",
answers: {
a: "Vulcan",
b: "Romulus",
c: "Ferenginar"
},
correctAnswer: "c",
inputType: "radio"
},
{ //Question 7
question: "Which transporter room is Chief Myles O'Brien's favourite?",
answers: {
a: "Transporter Room 3",
b: "Transporter Room 7",
c: "Transport Room 5"
},
correctAnswer: "a",
inputType: "radio"
},
{
//Question 8
question: "What is the name of the first ship that Jean Luc Picard captained?",
answers: {
a: "USS Enterprise",
b: "USS Stargazer",
c: "USS Defiant"
},
correctAnswer: "b",
inputType: "radio"
},
{
//Question 9
question: "Who does Commander Worf marry in Deep Space 9?",
answers: {
a: "Ezri Dax",
b: "Kera Nerys",
c: "Jadzia Dax"
},
correctAnswer: "c",
inputType: "radio"
},
{
//Question 10
question: "What is the name of The Borg Drone who joined Starfleet?",
answers: {
a: "Hugh",
b: "Seven of Nine",
c: "Icheb"
},
correctAnswer: "",
inputType: "radio"
}
];
// Kick things off
buildQuiz();
// Pagination
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
// Show the first slide
showSlide(currentSlide);
// Event listeners
submitButton.addEventListener('click', showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);