Creating a multiple choice quiz - javascript

I want to create a multiple-choice quiz with like 50 questions using HTML/JavaScript that only shows 1 question at a time. Right now, the previous radio button doesn't uncheck when I go to the next question and the 2nd question doesn't add to the total when I hit submit.
If I add another question to the "// Array of questions" the second question lists 8 radio buttons and the 3rd question never appears.
// Initialize the current question index
let currentQuestionIndex = 0;
// Array of questions
const questions = [{
question: "What is the capital of France?",
answers: [
{ text: "Paris", value: 1 },
{ text: "London", value: 0 },
{ text: "Rome", value: 0 },
{ text: "Madrid", value: 0 }
]
}, {
question: "What is the capital of Italy?",
answers: [
{ text: "Paris", value: 0 },
{ text: "London", value: 0 },
{ text: "Rome", value: 1 },
{ text: "Madrid", value: 0 }
]
}];
// Initialize the total score
let totalScore = 0;
// Add the value of the selected answer to the total score and uncheck the other radio buttons
function updateScore(selectedAnswer) {
// Check if a radio button has been selected
if (!selectedAnswer.checked) {
return;
}
// Add the value of the selected answer to the total score
totalScore += parseInt(selectedAnswer.value);
// Get all the radio buttons
const radioButtons = document.getElementsByName("answer");
// Loop through the radio buttons
for (const radioButton of radioButtons) {
// If the radio button is not the selected answer, uncheck it
if (radioButton !== selectedAnswer) {
radioButton.checked = false;
}
}
}
// Show the next question
function showNextQuestion() {
// Hide the form
document.getElementById("form").style.display = "none";
// Show the question and answers
document.getElementById("question").style.display = "block";
document.getElementById("answers").style.display = "block";
document.getElementById("next-button").style.display = "block";
// Check if the current question is the last question
if (currentQuestionIndex === questions.length - 1) {
// If it is, hide the "Next" button and show the "Submit" button
document.getElementById("next-button").style.display = "none";
document.getElementById("submit-button").style.display = "block";
} else {
// If it is not, get the current question
const currentQuestion = questions[currentQuestionIndex];
// Update the question text
document.getElementById("question").innerHTML = currentQuestion.question;
// Show the answers for the current question
for (const answer of currentQuestion.answers) {
document.getElementById("answers").innerHTML += `
<input type="radio" name="answer" value="${answer.value}" onchange="updateScore(this)"> ${answer.text}<br>
`;
}
// Update the current question index
currentQuestionIndex++;
}
}
// Show the total score
function showTotalScore() {
// Hide the question and answers
document.getElementById("question").style.display = "none";
document.getElementById("answers").style.display = "none";
document.getElementById("submit-button").style.display = "none";
// Show the total score
document.getElementById("total-score").style.display = "block";
document.getElementById("total-score").innerHTML = "Total Score: " + totalScore;
}
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for:="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="button" value="Next" onclick="showNextQuestion()">
</form>
<div id="question" style="display: none;"></div>
<div id="answers" style="display: none;"></div>
<div id="next-button" style="display: none;"><input type="button" value="Next" onclick="showNextQuestion()"></div>
<div id="submit-button" style="display: none;"><input type="button" value="Submit" onclick="showTotalScore()"></div>
<div id="total-score" style="display: none;">Total Score: 0</div>
I've tried adding a question to the array and it doesn't work the same.
I've tried adding radiobutton.checked = false; to a couple different places and it usually just doesn't generate the radio buttons at all.

You need a slight change in logic.
Change if (currentQuestionIndex === questions.length - 1) to if (currentQuestionIndex === questions.length) because you only want the buttons to change on the last question but the answers/questions still need to change
Move the if block from #1 after the current else at the end. The index will have incremented so the -1 isn't necessary
Change the now dangling else to if(currentQuestionIndex < questions.length){ so all questions are loaded
Before adding answers clear out previous answers with document.getElementById("answers").innerHTML = ''; otherwise answers will be additive (4 on question 1, 8 on question 2, etc)
// Initialize the current question index
let currentQuestionIndex = 0;
// Array of questions
const questions = [{
question: "What is the capital of France?",
answers: [
{ text: "Paris", value: 1 },
{ text: "London", value: 0 },
{ text: "Rome", value: 0 },
{ text: "Madrid", value: 0 }
]
}, {
question: "What is the capital of Italy?",
answers: [
{ text: "Paris", value: 0 },
{ text: "London", value: 0 },
{ text: "Rome", value: 1 },
{ text: "Madrid", value: 0 }
]
}];
// Initialize the total score
let totalScore = 0;
// Add the value of the selected answer to the total score and uncheck the other radio buttons
function updateScore(selectedAnswer) {
// Check if a radio button has been selected
if (!selectedAnswer.checked) {
return;
}
// Add the value of the selected answer to the total score
totalScore += parseInt(selectedAnswer.value);
// Get all the radio buttons
const radioButtons = document.getElementsByName("answer");
// Loop through the radio buttons
for (const radioButton of radioButtons) {
// If the radio button is not the selected answer, uncheck it
if (radioButton !== selectedAnswer) {
radioButton.checked = false;
}
}
}
// Show the next question
function showNextQuestion() {
// Hide the form
document.getElementById("form").style.display = "none";
// Show the question and answers
document.getElementById("question").style.display = "block";
document.getElementById("answers").style.display = "block";
document.getElementById("next-button").style.display = "block";
// Check if the current question is the last question
if(currentQuestionIndex < questions.length){
// If it is not, get the current question
const currentQuestion = questions[currentQuestionIndex];
// Update the question text
document.getElementById("question").innerHTML = currentQuestion.question;
//clear answers
document.getElementById("answers").innerHTML = '';
// Show the answers for the current question
for (const answer of currentQuestion.answers) {
document.getElementById("answers").innerHTML += `
<input type="radio" name="answer" value="${answer.value}" onchange="updateScore(this)"> ${answer.text}<br>
`;
}
// Update the current question index
currentQuestionIndex++;
}
if (currentQuestionIndex === questions.length) {
// If it is, hide the "Next" button and show the "Submit" button
document.getElementById("next-button").style.display = "none";
document.getElementById("submit-button").style.display = "block";
}
}
// Show the total score
function showTotalScore() {
// Hide the question and answers
document.getElementById("question").style.display = "none";
document.getElementById("answers").style.display = "none";
document.getElementById("submit-button").style.display = "none";
// Show the total score
document.getElementById("total-score").style.display = "block";
document.getElementById("total-score").innerHTML = "Total Score: " + totalScore;
}
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for:="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="button" value="Next" onclick="showNextQuestion()">
</form>
<div id="question" style="display: none;"></div>
<div id="answers" style="display: none;"></div>
<div id="next-button" style="display: none;"><input type="button" value="Next" onclick="showNextQuestion()"></div>
<div id="submit-button" style="display: none;"><input type="button" value="Submit" onclick="showTotalScore()"></div>
<div id="total-score" style="display: none;">Total Score: 0</div>

Related

Categorized Scoring of Questions

I want to take an array of questions in a quiz and categorize them into 3 different scores. Like Math/English/Science per-say.
So, if each of the 3 questions in the array was a separate category, can I label them and have a function that calculates based on category and how would that look?
I know I could duplicate my functions and slightly modify them based on the category, but I feel like there is a more efficient way to do that.
// Initialize the current question index
let currentQuestionIndex = 0;
// Array of questions
const questions = [{
question: "What does 2+2 equal?",
answers: [{
text: "4",
value: 1
},
{
text: "2",
value: 0
},
{
text: "8",
value: 0
},
{
text: "16",
value: 0
}
]
},
{
question: "What does oblitirate most nearly mean?",
answers: [{
text: "translate",
value: 0
},
{
text: "scatter",
value: 0
},
{
text: "wipe out",
value: 1
},
{
text: "blame",
value: 0
}
]
},
{
question: "What is the chemical formula for water?",
answers: [{
text: "H2O",
value: 0
},
{
text: "K",
value: 0
},
{
text: "Na",
value: 1
},
{
text: "H",
value: 0
}
]
}
];
// Initialize the total score
let totalScore = 0;
// Add the value of the selected answer to the total score and uncheck the other radio buttons
function updateScore(selectedAnswer) {
// Check if a radio button has been selected
if (!selectedAnswer.checked) {
return;
}
// Add the value of the selected answer to the total score
totalScore += parseInt(selectedAnswer.value);
// Get all the radio buttons
const radioButtons = document.getElementsByName("answer");
// Loop through the radio buttons
for (const radioButton of radioButtons) {
// If the radio button is not the selected answer, uncheck it
if (radioButton !== selectedAnswer) {
radioButton.checked = false;
}
}
}
// Show the next question
function showNextQuestion() {
// Hide the form
document.getElementById("form").style.display = "none";
// Show the question and answers
document.getElementById("question").style.display = "block";
document.getElementById("answers").style.display = "block";
document.getElementById("next-button").style.display = "block";
// Check if the current question is the last question
if (currentQuestionIndex < questions.length) {
// If it is not, get the current question
const currentQuestion = questions[currentQuestionIndex];
// Update the question text
document.getElementById("question").innerHTML = currentQuestion.question;
//clear answers
document.getElementById("answers").innerHTML = '';
// Show the answers for the current question
for (const answer of currentQuestion.answers) {
document.getElementById("answers").innerHTML += `
<input type="radio" name="answer" value="${answer.value}" onchange="updateScore(this)"> ${answer.text}<br>
`;
}
// Update the current question index
currentQuestionIndex++;
}
if (currentQuestionIndex === questions.length) {
// If it is, hide the "Next" button and show the "Submit" button
document.getElementById("next-button").style.display = "none";
document.getElementById("submit-button").style.display = "block";
}
}
// Show the total score
function showTotalScore() {
// Hide the question and answers
document.getElementById("question").style.display = "none";
document.getElementById("answers").style.display = "none";
document.getElementById("submit-button").style.display = "none";
// Show the total score
document.getElementById("total-score").style.display = "block";
document.getElementById("total-score").innerHTML = "Total Score: " + totalScore;
}
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="button" value="Next" onclick="showNextQuestion()">
</form>
<div id="question" style="display: none;"></div>
<div id="answers" style="display: none;"></div>
<div id="next-button" style="display: none;"><input type="button" value="Next" onclick="showNextQuestion()"></div>
<div id="submit-button" style="display: none;"><input type="button" value="Submit" onclick="showTotalScore()"></div>
<div id="total-score" style="display: none;">Total Score: 0</div>
You just need to create an object mapping each category to its score, and a category assigned to every question like so :
// Initialize the current question index
let currentQuestionIndex = 0;
// Array of questions
const questions = [{
question: "What does 2+2 equal?",
category: 'maths',
answers: [{
text: "4",
value: 1
},
{
text: "2",
value: 0
},
{
text: "8",
value: 0
},
{
text: "16",
value: 0
}
]
},
{
question: "What does oblitirate most nearly mean?",
category: 'english',
answers: [{
text: "translate",
value: 0
},
{
text: "scatter",
value: 0
},
{
text: "wipe out",
value: 1
},
{
text: "blame",
value: 0
}
]
},
{
question: "What is the chemical formula for water?",
category: 'science',
answers: [{
text: "H2O",
value: 1
},
{
text: "K",
value: 0
},
{
text: "Na",
value: 0
},
{
text: "H",
value: 0
}
]
}
];
// Initialize the total score
const scores = {}
let totalScore = 0
// Add the value of the selected answer to the total score and uncheck the other radio buttons
function updateScore (selectedAnswer, category) {
// Check if a radio button has been selected
if (!selectedAnswer.checked) return;
const v = parseInt(selectedAnswer.value)
// Add the value of the selected answer to the total score
totalScore += v;
// Add the value of the selected answer to the category score
scores[category] += v
// Get all the radio buttons
const radioButtons = document.getElementsByName("answer");
// Loop through the radio buttons
for (const radioButton of radioButtons) {
// If the radio button is not the selected answer, uncheck it
if (radioButton !== selectedAnswer) {
radioButton.checked = false;
}
}
}
// Show the next question
function showNextQuestion() {
// Hide the form
document.getElementById("form").style.display = "none";
// Show the question and answers
document.getElementById("question").style.display = "block";
document.getElementById("answers").style.display = "block";
document.getElementById("next-button").style.display = "block";
// Check if the current question is the last question
if (currentQuestionIndex < questions.length) {
// If it is not, get the current question
const currentQuestion = questions[currentQuestionIndex];
// Update the question text
document.getElementById("question").innerHTML = currentQuestion.question;
//clear answers
document.getElementById("answers").innerHTML = '';
// Init the category score
scores[currentQuestion.category] = 0
// Show the answers for the current question
for (const answer of currentQuestion.answers) {
document.getElementById("answers").innerHTML += `
<input type="radio" name="answer" value="${answer.value}" onchange="updateScore(this, '${ currentQuestion.category }')"> ${answer.text}<br>
`;
}
// Update the current question index
currentQuestionIndex++;
}
if (currentQuestionIndex === questions.length) {
// If it is, hide the "Next" button and show the "Submit" button
document.getElementById("next-button").style.display = "none";
document.getElementById("submit-button").style.display = "block";
}
}
// Show the total score
function showTotalScore() {
let txt = "Total Score: " + totalScore
console.log(scores)
Object.keys(scores).forEach(category => {
// Catpitalize the category
const categoryStr = category.split('').map((e, i) => i ? e : e.toUpperCase()).join('')
txt += `<br />${ categoryStr }: ${ scores[category] }`
})
// Hide the question and answers
document.getElementById("question").style.display = "none";
document.getElementById("answers").style.display = "none";
document.getElementById("submit-button").style.display = "none";
// Show the total score
document.getElementById("total-score").style.display = "block";
document.getElementById("total-score").innerHTML = txt;
}
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="button" value="Next" onclick="showNextQuestion()">
</form>
<div id="question" style="display: none;"></div>
<div id="answers" style="display: none;"></div>
<div id="next-button" style="display: none;"><input type="button" value="Next" onclick="showNextQuestion()"></div>
<div id="submit-button" style="display: none;"><input type="button" value="Submit" onclick="showTotalScore()"></div>
<div id="total-score" style="display: none;">Total Score: 0</div>

Javascript/HTMl Quiz - how do I add images to act as a potential answer

im currently trying to create a picture quiz that utlises this tutorial https://www.sitepoint.com/simple-javascript-quiz/
the issue I am having is changing this quiz from a solely text based affair into a picture quiz. for example the quiz will ask a question such as "which of these pictures is a giraffe?", the user then will have to select an answer that has a giraffe picture.
Below is the current version of the js script i have (admittedly, not much has changed, due to not being able to figure images out)
(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(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>`
);
}
);
// 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 = `${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 = '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);
}
// Variables
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [
{
question: "Who invented JavaScript?",
answers: {
a: "Douglas Crockford",
b: "Sheryl Sandberg",
c: "Brendan Eich"
},
correctAnswer: "a"
},
{
question: "is my name davet?",
answers: {
a: "Douglas Crockford",
b: "Sheryl Sandberg",
c: "yes"
},
correctAnswer: "c"
},
{
question: "Which one of these is a JavaScript package manager?",
answers: {
a: "Node.js",
b: "TypeScript",
c: "npm"
},
correctAnswer: "c"
},
{
question: "Which tool can you use to ensure code quality?",
answers: {
a: "Angular",
b: "jQuery",
c: "RequireJS",
d: "ESLint"
},
correctAnswer: "d"
}
];
// 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);
})();
Below is the current HTML I have
<h1>Quiz on Important Facts</h1>
<div class="quiz-container">
<div id="quiz"></div>
<img id="myImg">
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
<link href="newcss1.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap-reboot.rtl.min.css" type="text/css">
<script src="newjavascript.js" type="text/javascript"></script>

html javascript (game) how to retrieve value of button point is added when a button is clicked

i am creating a game. the game should work this way: when user click on the button with target option that was chosen previously from the dropdown list, score will +2, else -1.
however, the code i have now is not working, the score is not adding, its always 0. i am guessing it is because i didn't retrieve the value of the button correctly, hence, the value of the button chosen and target option value never match. how can i solve this issue??
background information: the 3 options will refresh every 1/2/3 seconds depending on the difficulty level chosen. hence, the option will always be different, there will also be situation where none of the 3 options is the target option. user can choose to wait for 1/2/3 seconds OR click on any of the option and receive a -1 point.
here is my code for the part where the score is calculated
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;
var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");
if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}
if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
document.getElementById("score").innerHTML = score;
}; //end of click
here is the entire code i have
<!DOCTYPE html>
<html>
<body>
<div>
<form name="start" id="start">
<table id="T">
<tr id="Ttitle"> <!-- Header -->
<th colspan="3"><h2>Assignment 3 Part 2: Game</h2></th>
</tr>
<tr id="Tplayer"> <!-- ROW 1 PLAYER NAME-->
<th>Player Name</th>
<td><!-- text box for Unique name -->
<input type="text" id="name" name="required name" placeholder="Enter your Name"><br>
<span style="color:red;" id="nameError"></span>
</td>
<td id="TS" rowspan="3"> <!-- TIMER AND SCORE -->
<h3>Time: </h3>
<div class="timeScore" ><span id="seconds">00</span>:<span id="tens">00</span> second(s)</div>
<h3>Score: </h3>
<div class="timeScore" ><span id="score">0</span></div>
</td> <!-- Time and Score -->
</tr>
<tr id="Ttarget"> <!-- ROW 2 TARGET OPTION-->
<th>The Target Option: </th>
<td> <!-- list box with all option -->
<select name="target_Opt" id="target_Opt">
<option value="">Choose your Target</option>
</select>
<span style="color:red;" id="TargetError"></span>
</td>
</tr>
<tr id="Tdifficulty"> <!-- ROW 3 DIFFICULTY LEVEL-->
<th>The Difficulty Level: </th>
<td id="radio"> <!-- Radio button Low, Med, High -->
<input type="radio" id="Low" name="difficulty" value="low" checked>
Low
<input type="radio" id="Medium" name="difficulty" value="med">
Medium
<input type="radio" id="High" name="difficulty" value="high">
High
</td>
</tr>
<tr id="Tbutton"> <!-- ROW 4 START STOP Button-->
<td colspan="3">
<input type="button" id="startBtn"
value="Start" >
<input type="button" id="stopBtn" value="Stop" >
</td>
</tr>
<tr id="Toptions"> <!-- ROW 5 CLICK Options -->
<td class="Opt">
<input type="button" class="gameOpt" id="TO1" value="Option 1" >
</td>
<td class="Opt">
<input type="button" class="gameOpt" id="TO2" value="Option 2" >
</td>
<td class="Opt">
<input type="button" class="gameOpt" id="TO3" value="Option 3" >
</td>
</tr>
</table>
<div id="Tlist" >
<h4> Player Listing : </h4>
<ul id="myList">
</ul>
</div>
</form> <!--END OF FORM WHEN START IS CLICKED -->
</div>
</body>
<script>
var score = 0; //for score
var pn = []; //Array to contain PlayerName
var ten = []; //Array for 10 Random Options
var a = document.forms["start"]["name"].value; //get Player's name input
var targetValue = document.getElementById("target_Opt").value; //selected target
//ARRAY OF OPTIONS TO CHOOSE TARGET
var Opt123 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var OptABC = ["A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "O",
"P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"];
//add options into dropdown list
function PrepopulateOpt() {
var selectTarget = document.getElementById("target_Opt");
var i = 1;
//add Opt123 into dropdown list
for (var target_Opt in Opt123) {
selectTarget.options[i++] = new Option(target_Opt);
}
//add OptABC into dropdown list
for (var i = 0; i < OptABC.length; i++) {
var opt = OptABC[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
selectTarget.appendChild(el);
}
}
PrepopulateOpt();
window.onload = function () {
var seconds = 00;
var tens = 00 ;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementById('startBtn');
var buttonStop = document.getElementById('stopBtn');
var Interval ;
var optionButton = document.getElementsByClassName('gameOpt'); //the options
//var changeOpt = document.getElementsByClassName("gameOpt").value; //option value
function ValidateEvent(){
var name = document.getElementById("name").value;
var target = document.getElementById("target_Opt").value;
//CHECK IF PLAYER NAME IS UNIQUE
if (name == null || name.trim() == "")
{
alert("Please enter your name");
return false;
} else if (pn.includes(name) == true){
alert("Please enter a unique name");
return false;
}
//CHECK IF TARGET IS SELECTED
if (target == "")
{
alert("Please select a target!") ;
return false;
}
else
{
document.getElementById("TargetError").value = "";
}
return true;
}
/* function removeDuplicates(data){
return data.filter((value, index) => data.indexOf(value) === index);
}
*/
function random10Opt(){
//targetValue = selected target value;
var target = document.getElementById("target_Opt").value;
//var target123 = parseInt(document.getElementById("target_Opt").value);
var index;
const newArr = [];
if (Opt123.includes(target) == true){
index = Opt123.indexOf(target);
Opt123.splice(index, 1);
return Opt123;
} else if (OptABC.includes(target) == true){
index = OptABC.indexOf(target);
OptABC.splice(index, 1);
return OptABC;
}
const a = Opt123.slice();
const b = OptABC.slice();
//select random 5 from digit add into newArr
for(let i= 5; i >= 0; i--){
let arr = a[Math.floor(Math.random()*a.length)];
let index = a.indexOf(arr);
a.splice(index, 1 );
newArr.push(arr);
}
for(let i= 5; i >= 0; i--){
let arr = b[Math.floor(Math.random()*b.length)];
let index = b.indexOf(arr);
b.splice(index, 1 );
newArr.push(arr);
}
newArr.push(target); //new array with randomized values : newArr
//enter random element into Option 1
var index1 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO1").value = index1;
var Arr2 = newArr.splice(index1, 1);
//enter random element into Option 2
var index2 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO2").value = index2;
var Arr3 = newArr.splice(index2, 1);
//enter random element into Option 3
var index3 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO3").value = index3;
console.log(newArr)
} //end of random10Opt
function difficultylvl() {
//TIME INTERVAL ACCORDING TO DIFFICULTY LEVEL
if (document.getElementById("Low").checked){
myVar = setInterval(random10Opt, 3000);
} else if (document.getElementById("Medium").checked){
myVar = setInterval(random10Opt, 2000);
} else {
myVar = setInterval(random10Opt, 1000);
}
} //end of difficulty level
//stop timeInterval for difficulty level
function stopInterval() {
clearInterval(myVar);
}
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;
var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");
if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}
if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
}
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
score = parseInt(document.getElementById("score").innerHTML);
score += 2;
//random10Opt;
} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}
document.getElementById("score").innerHTML = score;
}; //end of click
buttonStart.onclick = function() {
if( ValidateEvent() == true) {
//checkform(); //check name and target
random10Opt(); //add random value into button
difficultylvl(); //setInterval
addName(); //add player name into list
if (seconds == 00 && tens == 00){
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
} else {
clearInterval(Interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
}
}
};
buttonStop.onclick = function() {
clearInterval(Interval); //stop stopwatch
stopInterval(); //stop setInterval for options
//default value when the game stop
document.getElementById("TO1").value = "Option 1";
document.getElementById("TO2").value = "Option 2";
document.getElementById("TO3").value = "Option 3";
};
optionButton.onclick = function() {
clickScore(); //click the options for score
};
//stopwatch
function startTimer() {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
}//end of startTimer()
function addName(){
//takes the value of player name
//pn is an empty array to contain to names
var newArray = document.getElementById("name").value;
pn.push(newArray);
var node = document.createElement("LI");
var textnode = document.createTextNode(newArray);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
} //end of addName function
};//end on onload
</script>
</html>
you have registered the click-event twice.
just removed the onclick in the input
...
<input type="button" class="gameOpt" id="TO1" value="Option 1">
...
<input type="button" class="gameOpt" id="TO2" value="Option 2">
...
<input type="button" class="gameOpt" id="TO3" value="Option 3">
</td>
...
<script>
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);
Have a look at the snippet below, which I think illustrates what you're trying to accomplish.
Your buttons will be randomized at the outset. Then you can choose the "target value" from the drop-down, and clicking the button w/the value that matches your selected "target value" will add points, whereas clicking a button that doesn't match the target value will subtract points.
Note how much simpler it becomes to attach the click event handler in a way that allows you to read the event target's value.
var score = 0;
var newArr = [1, 2, 3, 4, 5, "A", "B", "C", "D", "E"];
let scoreOutput = document.getElementById("scoreUpdate");
const gameButtons = document.querySelectorAll(".gameOpt");
//this code just creates the select dropdown, which you don't need to do
var select = document.getElementById("targetValue");
for (var i = 0; i < newArr.length; i++) {
var opt = newArr[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
randomizeButtonValues();
//attach the click for each button
[...gameButtons].forEach((btn) => {
btn.addEventListener("click", (e) => {
let correctValue = document.getElementById("targetValue").value;
let clickedValue = e.target.value; // <-- capture value of clicked element
console.log(correctValue, clickedValue);
if(correctValue == clickedValue) {
score += 2;
} else {
score -= 1;
}
scoreOutput.innerHTML += `<br>New Score: ${score}`;
randomizeButtonValues();
});
});
function randomizeButtonValues() {
[...gameButtons].forEach((btn) => {
let rnd = Math.floor(Math.random() * newArr.length);
btn.value = newArr[rnd];
});
}
<select id="targetValue">
<option>Choose target value</option>
</select>
<input type="button" class="gameOpt" id="TO1" value="Option 1">
<input type="button" class="gameOpt" id="TO2" value="Option 2">
<input type="button" class="gameOpt" id="TO3" value="Option 3">
<br>
<div id="scoreUpdate"></div>

how to increase question number and score count

I am making a quiz app and i was trying to increase the question number and score every time they go to the next question. Also would like to give some feed back when they get it the question right or wrong. Any tips will be greatly appreciated. New to coding and really trying to figure this all out
let currentQuestion = 0;
let score = 1;
function renderQuestion() {
document.getElementById("quiz").innerHTML =
`
<fieldset>
<legend> ${questions[currentQuestion].question} </legend>
<input type="radio" name="option"
value="A">${questions[currentQuestion].options[0].option}<br>
<input type="radio" name="option"
value="B">${questions[currentQuestion].options[1].option}<br>
<input type="radio" name="option"
value="C">${questions[currentQuestion].options[2].option}<br>
<input type="radio" name="option"
value="D">${questions[currentQuestion].options[3].option}<br>
<button id="button" class="submitAnswer"> Submit answer </button>
<div id="errorMessage">
</div>
<div id="feed">
</div>
</fieldset>
`;
document.getElementById("button").addEventListener("click",
function(event) {
event.preventDefault();
let hasAnswer = false;
for (let el of document.querySelectorAll("input")) {
if (el.checked) {
hasAnswer = true;
if (el.value === questions[currentQuestion].answer)
{
score++;
}
}
}
if (hasAnswer) {
if (currentQuestion === questions.length - 1) {
document.getElementById("quiz").innerHTML = `Your score is
${score}`;
}
else {
currentQuestion++;
renderQuestion();
}
}
else {
document.getElementById("errorMessage").innerHTML = "Please
select an answer!";
}
});
}
renderQuestion();
If you want to increase the score every time they move to the next question, the easiest way would be to add this:
score++;
Inside this:
else {
currentQuestion++;
score++;
renderQuestion();
}
Which is inside this block:
if (hasAnswer) {
if (currentQuestion === questions.length - 1) {
document.getElementById("quiz").innerHTML = `Your score is
${score}`;
}
else {
currentQuestion++;
score++;
renderQuestion();
}
}
else {
document.getElementById("errorMessage").innerHTML = "Please
select an answer!";
}
Hopefully this helps!

Checking radio buttons according to an Array

I have an array containing four numbers:
var players = [0,3,4,2];
I have some radio buttons to select a name:
<h3 id="question">Which player would you like?</h3>
<input type="radio" name="choice" value="0" id="answ1">
<label for="choice" id="choice_1">John</label>
<br>
<input type="radio" name="choice" value="1" id="answ2">
<label for="choice" id="choice_2">Wayne</label>
<br>
<input type="radio" name="choice" value="2" id="answ3">
<label for="choice" id="choice_3">Steven</label>
<br>
<input type="radio" name="choice" value="3" id="answ4">
<label for="choice" id="choice_4">Jack</label>
<br>
<button id="back">Back</button>
<button id="next">Next</button>
When the radio buttons display I would like the first radio button to be checked i.e. The player John. I know I could simply set autofocus or use jQuery but I want to do it with vanilla Javascript. The idea is that the player names will change dynamically and the player will be selected based on the value in the array i.e. number 3 of the second set of players will be chosen.
Thanks, any help appreciated.
EDIT:
John will be chosen because the first value of the array is 0 and John is the first choice i.e. 0 = 1st choice, 1 = second choice etc
You need to increment/decrement an index value when the Next/Back buttons are clicked, and then set the checked property to true for the radio button with that index.
var players = [0, 3, 4, 2, 1];
var i = 0;
var choices = document.querySelectorAll('input[name="choice"]');
choices[players[i]].checked = true;
document.getElementById('back').onclick = function () {
if (i > 0) {
i--;
choices[players[i]].checked = true;
}
}
document.getElementById('next').onclick = function () {
if (i < players.length - 1) {
i++;
choices[players[i]].checked = true;
}
}
DEMO
You can try my approach using array.indexOf
var players = [0, 3, 4, 2];
var ins = document.getElementsByName('choice');
for (var i = 0; i < ins.length; i++) {
if (players.indexOf(parseInt(ins[i].value, 10)) > -1) {
ins[i].checked = true;
}
}
FYI:
The radio button is grouped under the name check so multiple
select is not going to work in your case.
This code will fail in older version of IE and here is the workaround.
You can do this like this:
var players = [0,3,4,2];
var firstValue = players[0];
var firstInput = document.querySelector("input[type=radio][name=choice][value='"+firstValue+"']");
firstInput.checked = true;
var players = [0,3,1,2];
var currentPosInArray = 0;
window.onload = function() {
ChangeSelectedRadio();
}
function ChangeSelectedRadio() {
var radio = document.querySelectorAll("input[type='radio']");
var arrItem = players[currentPosInArray];
for (var i =0; i< radio.length; i++ ){
radio[i].checked = false;
}
if (radio[arrItem]) {
radio[arrItem].checked = true;
}
}
function ChangeSelection(forward) {
if (forward) {
currentPosInArray++;
}
else {
currentPosInArray--;
}
if (currentPosInArray < 0) {
currentPosInArray = players.length -1; //if is in first pos and click "Back" - go to last item in array
}
else if (currentPosInArray >= players.length) {
currentPosInArray = 0; //if is in last position and click "Next" - go to first item in array
}
ChangeSelectedRadio();
}
where ChangeSelection(forward) is event to buttons.
DEMO: http://jsfiddle.net/9RWsp/1/

Categories

Resources