Before I start explaining please understand I am relatively new to coding, so please don't rag on me to bad, lol.
I am building a quiz that is multiple choice all of the quiz is working except for the part that is supposed to show the question explanation when the next button is clicked. When I add the code to the output.push() it appears on the screen and loops through it but my buttons stop working. I am not sure why they stop working.
I also need a way to hide the question explanation until the user has clicked an answer. Any help would be appreciated, thanks in advance.
window.onload = function() {
(function() {
// Functions
function buildQuiz() {
// variable to store the HTML output
const output = [];
// for each question...
myQuestions.forEach(
(currentQuestion, questionNumber) => {
// variable to store the list of possible answers
const answers = [];
// and for each available answer...
for (var letter in currentQuestion.answers) {
// ...add an HTML radio button
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
output.push(
`<div class="slide">
<div class="question"> ${currentQuestion.question}
</div>
<div class="answers"> ${answers.join("")} </div>
</div>`
)
);
// <div
class="explanationOne">${currentQuestion.explanation.correct}
</div>
// <div
class="explanationTwo">${currentQuestion.explanation.explain}
</div>
// <div
class="explanationOne">${currentQuestion.explanation.source}
</div>
document.write(); document.write(output.push($ {
currentQuestion.explanation.correct
}));
}
);
// 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) => {
// 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';
}
});
// show number of correct answers out of total
resultsContainer.innerHTML = 'Your Score:' + ' ' +
`${numCorrect} out of
${myQuestions.length}`;
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.style.display = 'inline-block';
nextButton.style.display = 'inline-block';
submitButton.style.display = 'inline-block';
document.getElementById("submit").disabled = true;
document.getElementById("previous").disabled = true;
} else {
submitButton.style.display = 'inline-block';
document.getElementById("submit").disabled = false;
document.getElementById("previous").disabled = false;
}
if (currentSlide === slides.length - 1) {
previousButton.style.display = 'inline-block';
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
document.getElementById("submit").disabled = false;
} else {
previousButton.style.display = 'inline-block';
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
function showExplanation() {
var x = document.getElementById('explanations');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
};
// Variables
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const explainQuestion = document.getElementById('explanation');
const myQuestions = [{
question: "What color is the sky",
answers: {
a: "blue",
b: "green",
c: "yellow",
d: "orange"
},
explanation: {
correct: "Correct answer: A. Yep the sky is blue",
explain: "Everyone knows that.
",
source: "Your brain"
},
correctAnswer: "a"
},
{
question: "What time do you wake up in the morning?",
answers: {
a: "Noon",
b: "6 AM - 8 AM",
c: "9 AM - 11 AM",
d: "After noon"
},
explanation: {
correct: "Correct answer: B. The early bird gets the
worm.",
explain: "If you get up early you more likely to be
successful.
",
source: "life experience!"
},
correctAnswer: "b"
},
];
// Kick things off
buildQuiz();
// Pagination
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const submitButton = document.getElementById('submit');
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
// Show the first slide
showSlide(currentSlide);
// Event listeners
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
submitButton.addEventListener('click', showResults);
// nextButton.addEventListener("click", myQuestions.explanation.correct);
// nextButton.addEventListener("click", myQuestions.explanation.explain);
// nextButton.addEventListener("click", myQuestions.explanation.source);
})();
}
<body>
<!-- START OF QUIZ-->
<div id="border" class="uk-align-center uk-width-1-2">
<div class="quiz-body">
<h1 class="h1-quiz">Test Your Knowledge</h1>
<div class="quiz-container">
<div id="quiz"></div>
</div>
<div id="buttonGroup" class="uk-width-1-1 uk-align-center">
<button id="previous" class="uk-text-center">Previous </button>
<button id="next" class="uk-text-center">Next </button>
<button id="submit" class="uk-text-center">Submit </button>
</div>
<div class="explanationOne"> </div>
<div class="explanationTwo"></div>
<div class="explanationOne"></div>
<div id="results" class="uk-text-center uk-text-large uk-text-bold uk-margin-small-top">
</div>
<div class="uk-text uk-text-small uk-text-center">If you click the previous button once the quiz is complete the questions you answered correctly turn green and the incorrect answers are red.</div>
</div>
</div>
<!--END OF QUIZ-->
<br/>
<script src="code.js"></script>
</body>
just done the basic of showing explanations when clicked on label.
https://codesandbox.io/s/epic-poitras-ldyxk?file=/src/index.js
The code is too big to paste here. Attaching screenshot.
Related
I am working with program that will randomly choose who is making a Christmas gift to whom.
I've created an empty array. When you add a "player" it's pushing the name into two different arrays. Players[] and Players2[].
When you start a draw. The program writes the names of the Players[] on the left hand side and on the right side it writes the drawn names from Players2[].
Every Player from Players2[], after being drawn, is being deleted from the array so in the end we have an empty Players2[] array and full Players[] array.
The problem is: I can't make a working if statement that is checking if the person will not draw himself...
let Players = [];
let Players2 = [];
const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');
addBTN.addEventListener('click', function() {
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
console.log('error_empty_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Wpisz imię osoby!";
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Dodaj kolejną osobę.";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
});
refreshBTN.addEventListener('click', function() {
document.getElementById('warning').style.display = "block";
});
warningBTNyes.addEventListener('click', function() {
location.reload(true);
document.getElementById('addPLAYER').value = "";
});
warningBTNno.addEventListener('click', function() {
document.getElementById('warning').style.display = "none";
});
startBTN.addEventListener('click', function() {
drawLotsBTN.disabled = false;
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Zaczynasz losowanie!";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
document.getElementById('addPLAYER').disabled = true;
});
drawLotsBTN.addEventListener('click', function() {
for (let i = 0; i = Players2.length; i++) {
if (Players2.length > 0) {
randomPerson = Math.floor(Math.random() * Players2.length);
if (randomPerson != Players.indexOf(i)) {
console.log(Players2[randomPerson]);
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
Players2.splice(randomPerson, 1);
}
} else {
console.log('error_empty_array');
}
}
});
<div id="warning" class="warning">
<div class="warning-flex">
<h1>Wszelkie wpisane imiona zostaną usunięte</h1>
<div class="warning-buttons">
<button id="warning-button-yes" class="warning-button-yes">Tak</button>
<button id="warning-button-no" class="warning-button no">Nie</button>
</div>
</div>
</div>
<div class="lotteryContainer">
<div class="left">
<p>dodaj osobę</p>
<div class="addPerson">
<input required id="addPLAYER" type="text">
<button id="addBTN">+</button>
<p id="errorMSG"></p>
<div class="refresh">
<button id="refreshBTN">Od nowa</button>
<button id="startBTN">Start</button>
</div>
</div>
</div>
<div class="right">
<p>Uczestnicy</p>
<div class="tables">
<div class="tableLeft">
<p id=playersList></p>
</div>
<div class="tableRight">
<p id="playersList2"></p>
</div>
</div>
<button id="drawLotsBTN">Losuj</button>
</div>
</div>
<script src="app.js"></script>
Now if I understand what your program aims to do, there is a simple algorithm for it.
How I understand your goal:
You have a list of persons who are going to give presents to each other. (like in secret Santa). It is random who will give to who, but each person gives and receives one gift.
How to implement it (i'd normaly use maps, but I am guessing you are more comfortable with arrays):
players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffles array
gives_to = [...players]; // copy values of array
gives_to.push(gives_to.shift()); // let the first element be the last
Here the first player (players[0]) will give to gives_to[0] and the second to gives_to[1] etc.
I've created this JS script trying to use Trygve Ruud algorithm but it doesn't work like desired.
drawLotsBTN.addEventListener('click', function(){
if(Players.length > 0) {
console.log(Players)
Players.sort(function(a, b){
return 0.5 - Math.random();
});
for(let i = 0; i < Players.length; i++){
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
}
}
else{
console.log('error_empty_array');
}
});
So i have following objectives from the checkbox click event
1] Create A Button having id = 'id-of-checkbox'+'some-character-here' in specified div
2] Clicking On That Particular Button Will Remove The Button As Well As Checkbox tick related to it
3] If User wants to remove button in specified div through unchecking the checkbox it should be done
4] And If User again checks the checkbox button should be created in specified div
Now i have achieved first 3 objectives and im having issue with 4th one , i.e
if i click on checkbox again after unticking it button is not getting created and console doesnt return any error associated with it.. please help
Here Is My HTML Code
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)">
Price Filter
</div>
<div id="DropArea">
</div>
Here is My Javascript Code
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id,name)
{
if(document.getElementById(id).checked)
{
checked='yes'
}
else if(!document.getElementById(id).checked)
{
checked='no'
}
if(checked=='yes')
{
addButton(id,name);
}
else if(checked=='no')
{
removeButton(id,name);
}
}
function addButton(id,name)
{
var nameOfButton = name+'X';
var idofButton = id+'11';
var btn = document.createElement("BUTTON");
btn.innerHTML=nameOfButton;
btn.setAttribute("class","btnCancel");
btn.setAttribute("id",idofButton);
btn.setAttribute("onclick","someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id,name)
{
var idofButton = id+'11'
if(document.getElementById('DropArea').contains(document.getElementById(idofButton)))
{
document.getElementById('DropArea').remove(document.getElementById(idofButton));
console.log('Button Removed');
}
}
function someMsg(id)
{
var name = id.substring(0,id.length-2);
document.getElementById(id).remove();
document.getElementById(name).checked=false;
console.log('Deleted');
}
Another approach to achieving the same result:
const dropArea = document.querySelector("#dropArea");
const checkbox = document.querySelector("#priceFilter");
checkbox.addEventListener("change", function(e) {
if (this.checked) {
const btn = createSpecificButton();
dropArea.appendChild(btn);
} else {
const btn = dropArea.querySelector("button");
dropArea.removeChild(btn);
}
});
const createSpecificButton = () => {
const btn = document.createElement("button");
btn.innerText = "Click Here";
btn.addEventListener("click", function(e) {
checkbox.checked = false;
this.remove();
});
return btn;
};
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" /> Price Filter
</div>
<div id="dropArea"></div>
Element.remove() don't have any parameters, so when you call by your way, it will remove DropArea element (includes children, like idofButton).
Solution: Change the below line
document.getElementById('DropArea').remove(document.getElementById(idofButton));
To
document.getElementById(idofButton).remove();
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id, name) {
if (document.getElementById(id).checked) {
checked = 'yes'
} else if (!document.getElementById(id).checked) {
checked = 'no'
}
if (checked == 'yes') {
addButton(id, name);
} else if (checked == 'no') {
removeButton(id, name);
}
}
function addButton(id, name) {
var nameOfButton = name + 'X';
var idofButton = id + '11';
var btn = document.createElement("BUTTON");
btn.innerHTML = nameOfButton;
btn.setAttribute("class", "btnCancel");
btn.setAttribute("id", idofButton);
btn.setAttribute("onclick", "someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id, name) {
var idofButton = id + '11'
if (document.getElementById('DropArea').contains(document.getElementById(idofButton))) {
document.getElementById(idofButton).remove();
console.log('Button Removed');
}
}
function someMsg(id) {
var name = id.substring(0, id.length - 2);
document.getElementById(id).remove();
document.getElementById(name).checked = false;
console.log('Deleted');
}
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)"> Price Filter
</div>
<div id="DropArea">
</div>
I have created a simple quiz, as below:
var myQuestions = [
{
question: "Question1 would go here",
answers: {
a: 'Yes',
b: 'No',
},
correctAnswer: 'b'
},
{
question: "Question2 would go here",
answers: {
a: 'Yes',
b: 'No',
},
correctAnswer: 'b'
}
];
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);
function generateQuiz(questions, quizContainer, resultsContainer, submitButton){
function showQuestions(questions, quizContainer){
// we'll need a place to store the output and the answer choices
var output = [];
var answers;
// for each question...
for(var i=0; i<questions.length; i++){
// first reset the list of answers
answers = [];
// for each available answer...
for(letter in questions[i].answers){
// ...add an html radio button
answers.push(
'<label>'
+ '<input type="radio" name="question'+i+'" value="'+letter+'">'
+ questions[i].answers[letter]
+ '</label>'
);
}
// add this question and its answers to the output
output.push(
'<div class="question">' + questions[i].question + '</div>'
+ '<div class="answers">' + answers.join('') + '</div>'
);
}
// finally combine our output list into one string of html and put it on the page
quizContainer.innerHTML = output.join('');
}
function showResults(questions, quizContainer, resultsContainer){
// gather answer containers from our quiz
var answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
var userAnswer = '';
var numCorrect = 0;
// for each question...
for(var i=0; i<questions.length; i++){
// find selected answer
userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
// if answer is correct
if(userAnswer===questions[i].correctAnswer){
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[i].style.color = 'lightgreen';
}
// if answer is wrong or blank
else{
// color the answers red
answerContainers[i].style.color = 'red';
}
}
// show number of correct answers out of total
resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
}
// show questions right away
showQuestions(questions, quizContainer);
// on submit, show results
submitButton.onclick = function(){
showResults(questions, quizContainer, resultsContainer);
}
}
<div id="quiz"></div>
<button id="submit">Get Results</button>
<div id="results"></div>
However, I am trying to make it do 3 things:
Instead of showing the score of the quiz, I want ONE Message to display for Pass and ONE message to display for Fail.
I want it that if ALL questions are answered correctly, then it is a Pass, otherwise it is a Fail.
I do not want the user to submit the quiz until ALL questions have an answer.
Any help with the above modifications would be greatly appreciated. thanks
Try this:
I am using the built-in required and onsubmit event of forms in html to make sure the user answered all questions.
If there is anything else you need done with this answer please send a comment.
var myQuestions = [
{
question: "Question1 would go here",
answers: {
a: 'Yes',
b: 'No',
},
correctAnswer: 'b'
},
{
question: "Question2 would go here",
answers: {
a: 'Yes',
b: 'No',
},
correctAnswer: 'b'
}
];
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);
function generateQuiz(questions, quizContainer, resultsContainer, submitButton){
function showQuestions(questions, quizContainer){
// we'll need a place to store the output and the answer choices
var output = [];
var answers;
// for each question...
for(var i=0; i<questions.length; i++){
// first reset the list of answers
answers = [];
// for each available answer...
for(letter in questions[i].answers){
// ...add an html radio button
answers.push(
'<label>'
+ '<input type="radio" name="question'+i+'" value="'+letter+'" required="true">'
+ questions[i].answers[letter]
+ '</label>'
);
}
// add this question and its answers to the output
output.push(
'<div class="question">' + questions[i].question + '</div>'
+ '<div class="answers">' + answers.join('') + '</div>'
);
}
// finally combine our output list into one string of html and put it on the page
quizContainer.innerHTML = output.join('');
quizContainer.innerHTML += `<input id="submit" type="submit" value="Get Results">`;
}
function showResults(questions, quizContainer, resultsContainer){
// gather answer containers from our quiz
var answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
var userAnswer = '';
var numCorrect = 0;
// for each question...
for(var i=0; i<questions.length; i++){
// find selected answer
userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
// if answer is correct
if(userAnswer===questions[i].correctAnswer){
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[i].style.color = 'lightgreen';
}
// if answer is wrong or blank
else{
// color the answers red
answerContainers[i].style.color = 'red';
}
}
// show number of correct answers out of total
resultsContainer.innerHTML = numCorrect == myQuestions.length ? "Pass" : "Fail"
}
// show questions right away
showQuestions(questions, quizContainer);
document.querySelector("#quiz").addEventListener("submit", e => {
showResults(questions, quizContainer, resultsContainer);
});
}
<form id="quiz" action="javascript:void(0);">
<input id="submit" type="submit" value="Get Results">
</form>
<div id="results"></div>
<!DOCTYPE html>
<html>
<body>
<p id="Image"></p>
Basically what im tryijngto do s
One fix I'd recommend would be splitting your logic into two functions, one the user clicks to check their answer, and one they click to see the next question. This will allow you to display the congrats message on the screen rather than in an alert. Here is that in action:
let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
checkMessage.clear();
input.value = '';
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
button.setAttribute('onclick','checkAnswer()');
button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
gameScore.add();
} else {
checkMessage.set('SORRY, IT WAS INCORRECT');
gameScore.subtract();
}
questionsAsked++;
button.setAttribute('onclick','askQuestion()');
button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>
If you would prefer to keep everything in one function and use alerts for the congrats message, you can do so by keeping track of then number of questions asked, and not instantly checking the answer on the first load, like this:
let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
questionsAnswered++;
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
if (questionsAnswered) {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
gameScore.add();
alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
} else {
gameScore.subtract();
alert('SORRY, IT WAS INCORRECT');
}
questionsAnswered++;
}
imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />
Both solutions would work fine with alerts, though the first solution offers some greater flexibility for any functions you make want to perform in between questions. One other main fix there was to make here was to check change the image after checking the answer, and also making sure to actually fun the function in the beginning using askQuestion() in this case. I also added a couple of handy functions gameScore.add() and gameScore.subtract() to ease future use.
You can pass in other integers such as gameScore.add(2) if you every wanted to have double-weighted questions. I also added a Math.max() line to ensure the score never passes below 0. You can remove this if you would like the player's score to pass into negative numbers.
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
<img id="Image" src="#" width="250" height="250">
<br>
<br>
<input id="userInput" type="text">
<br>
<br>
<button type="button" id="btn" onclick="startGame()">Start Game</button>
<span id="GameScore">Score:</span>
<script>
let score = 10;
var Chad = "Chad.jpg";
let begin = 1;
let thePhoto;
var someArray = [ Chad, Bob
];
function startGame() {
if (start == 0) {
for (var l = 2; i < 3; i--) {
randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = randomPhoto;
document.getElementById("btn").innerHTML = "Submit";
start = 1;
}
} else {
randomPhoto = randomPhoto.replace(".jpg", "Insert");
}
else {
for (var x = 0; i < 3; i++) {
TheName = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = theName;
alert("No");
scorex = score-1;
}
document.getElementById("theScore").innerHTML="Score: "+score;
</script>
</body>
</html>
I have a Javascript Q&A Quiz working but I have one issue that must be solved.
I need to make the answer required before going to the next question, I really don't know how to make this work.
I got this code from this source, but I have changed a few things. https://codepen.io/SitePoint/pen/GmPjjL
HTML:
<div class="quiz-container">
<div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
JS:
(function() {
const myQuestions = [
{
question: "Question 1",
answers: {
a: "answer a",
b: "answer b",
},
correctAnswer: "a"
},
{
question: "question 2",
answers: {
a: "answer a",
b: "answer b",
},
correctAnswer: "a"
}
];
function buildQuiz() {
const output = [];
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.answers) {
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
output.push(
`<div class="slide">
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`
);
});
quizContainer.innerHTML = output.join("");
}
function showResults() {
const answerContainers = quizContainer.querySelectorAll(".answers");
let numCorrect = 0;
myQuestions.forEach((currentQuestion, questionNumber) => {
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if (userAnswer === currentQuestion.correctAnswer) {
numCorrect++;
answerContainers[questionNumber].style.color = "#333333";
} else {
answerContainers[questionNumber].style.color = "#333333";
}
});
var premio;
if(numCorrect == 0)
{
premio = '<div><span style="color: red">RESULT 0</span></div>'; }
else if(numCorrect == 1) { premio = '<div>RESULT 1</div>'; }
document.getElementById("quiz").style.display = "none";
document.getElementById("previous").style.display = "none";
document.getElementById("submit").style.display = "none";
resultsContainer.innerHTML = `RESULT <span class="resultadonum">${numCorrect}</span>` + premio; //de ${myQuestions.length}//
}
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);
}
const quizContainer = document.getElementById("quiz");
const resultsContainer = document.getElementById("results");
const submitButton = document.getElementById("submit");
buildQuiz();
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
showSlide(0);
submitButton.addEventListener("click", showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
Your best bet is to use the disabled attribute for your button.
Hook the disabled up to a function that checks whether or not the user has entered anything. Review your answers container around line 77 for the relevant code to check if the user has entered anything.
Psudo Code
function checkIfUserEnteredAnything(currentSlide){
//Code to calculate how many questions total the user has answered.
if(currentSlide === numQuestionsUserAnswered){
return true}
return false
Then, you'll set up your button to be disabled if the user hasn't entered anything.
nextButton.setAttribute('disabled',!checkIfUserEnteredAnything(currentSlide))
The exclamation point denotes the "not" function; if your function returns true (the user has entered a value), then it will become false-- telling the next button that it should not be disabled. If your function returns false, then the user has NOT entered a value, and it will tell the button to be disabled.