Categorized Scoring of Questions - javascript

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>

Related

Creating a multiple choice quiz

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>

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>

For loop loses variable value after first loop [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 5 years ago.
Apologies if my question title is not accurate, I couldn't think how to phrase it.
var options = [2,3,4]
// select drop down
var select = document.getElementById("itemSet");
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
select.add(el);
}
// define arrays
var arrActivity = ["alien monster", "man in business suit levitating", "fencer", "horse racing", "skier", "snowboarder", "golfer", "surfer", "rowboat", "swimmer"];
var arrFood = ["grapes", "melon", "watermelon", "tangerine", "lemon", "banana", "pineapple", "red apple", "green apple", "pear"];
var arrObjects = ["skull and crossbones", "love letter", "bomb", "hole", "shopping bags", "prayer beads", "gem stone", "hocho", "amphora", "world map"];
var arrLetters = ["letter a", "letter b", "letter c", "letter d", "letter e", "letter f", "letter g", "letter h", "letter i", "letter j"];
// format the array data for output into the textarea
function boom() {
var e = document.getElementById("itemSet");
var myCols = e.options[e.selectedIndex].value;
console.log(myCols);
var arrNew = [];
if (document.getElementById("radioActivity").checked) {
y = arrActivity;
} else if (document.getElementById("radioFood").checked) {
y = arrFood;
} else if (document.getElementById("radioObjects").checked) {
y = arrObjects;
} else if (document.getElementById("radioLetters").checked) {
y = arrLetters;
}
for (var i = 0; i < y.length; i += myCols) {
arrNew.push(
y.slice(i, i + myCols)
);
}
// set the textarea output
op = JSON.stringify(arrNew, null, 4);
document.getElementById('output').value = op;
}
<form onSubmit="return false;">
<label class="radio-inline">
<input type="radio" name="myArray" id="radioActivity" value="valActivity"> Activity
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioFood" value="arrFood"> Food
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioObjects" value="arrObjects"> Objects
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioLetters" value="arrLetters"> Letters
</label>
<select class="form-control" id="itemSet" name="itemSet"></select>
<button onClick="boom();"> Check Radio </button>
<textarea id="output" class="form-control" style="width:95%; height:500px; margin-top:20px;"></textarea>
</form>
When I click the "Check Radio" button, I want to reformat the arrays into chunks using this for loop:
for (var i = 0; i < y.length; i+=myCols) {
arrNew.push(
y.slice(i, i+myCols)
);
}
If I submit the form with a select value of e.g. 2 then the array is reformatted as:
[
[
"alien monster",
"man in business suit levitating"
],
[
"fencer",
"horse racing",
"skier",
"snowboarder",
"golfer",
"surfer",
"rowboat",
"swimmer"
]
]
Instead of in chunks of 2:
[
[
"alien monster",
"man in business suit levitating"
],
[
"fencer",
"horse racing"
],
[
"skier",
"snowboarder"
],
[
"golfer",
"surfer"
],
[
"rowboat",
"swimmer"
]
]
This CodePen demonstrates the issue: https://codepen.io/paperknees/pen/boXjXW
I can't work out what I'm doing wrong.
myCols is a string, therefore
y = 0;
myCols = "2"
//first iteration
y += myCols // "2"
//second iteration:
y += myCols // "22"
To solve this, add an unary plus operator:
var myCols = +e.options[e.selectedIndex].value;
You'll get it here -
while (y.length > 0)
arrNew.push(y.splice(0, myCols))
console.log(arrNew);
That's it!

Getting the value of "on" for radio buttons

var allQuestions = [{
question1: "What is 1 + 1?",
choices: ["1", "2", "3", 4],
correctAnswer: ["2"]
}, {
question2: "What is 2 + 2?",
choices: ["6", "2", "3", 4, ],
correctAnswer: ["4"]
}, {
question3: "What is 3 + 3?",
choices: ["3", "6", "9", 12],
correctAnswer: ["6"]
}];
var newArray = shuffleArray(allQuestions);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function appendQuestions(number) {
if (newArray == "undefined" || newArray == "null" || newArray.length == 0) {
document.getElementById("questionForm").innerHTML = "Complete!";
} else {
for (i = 0; i < 4; i++) {
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>")
}
}
}
$(function() {
$("#questionList").empty();
appendQuestions();
newArray.shift();
})
function isCorrectAnswer() {
checkedVal = $("input[type=radio][name=question]:checked").val();
if (checkedVal == newArray[0].correctAnswer) {
alert("Correct!");
} else {
alert("Wrong!");
}
alert(checkedVal);
}
$("#submitButton").click(function() {
isCorrectAnswer();
$("#questionForm").empty();
appendQuestions();
newArray.shift();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<section id='questions'>
<form id="questionForm">
</form>
<div style='clear:both'></div>
<input id='submitButton' type='button' value='Submit'>
</section>
</div>
First off, sorry for the amount of code pasted. I have no idea if I'm missing some small bug or if I'm just writing the wrong code, so I figured it would be best to post all of it.
I am trying to get the value of a radio button. In the isCorrectAnswer function the first 2 lines are to determine the value of the radio button that is currently checked. The problem is when I alert the value of the radio button, it just says "on". I have searched for the last hour trying to figure out what this means or how to fix it and could not find a thing.
I apologize if this is a stupid question or if it has already been answered.
You have to change this line :
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>");
To :
$("#questionForm").append("<input name='question' type='radio' value='" +
JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));
Hope this helps.

Quizgame selection doesn't work properly in Javascript

I tried to create a little quizgame in Javascript and HTML but it doesn't work properly yet. If I select the correct answer and let it validate, i get a wrong output. In my function showExercise I tried to set the possible answers always in a different order when it gets invoked. Thus the user is not able to select the right answers by a pattern. I am thankful for any suggetions and corrections.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Quizgame</title>
</head>
<body>
<h1>Quizgame</h1>
<form>
<fieldset>
<legend id="question">Quizgame</legend>
<input type="radio" name="choice" id="1" value="1">
<label for="1">Placeholder</label><br>
<input type="radio" name="choice" id="2" value="2">
<label for="2">Placeholder</label><br>
<input type="radio" name="choice" id="3" value="3">
<label for="3">Placeholder</label><br>
<input type="radio" name="choice" id="4" value="4">
<label for="4">Placeholder</label><br>
<button onclick="validateInput()">Check</button>
</fieldset>
</form>
<script type="text/javascript">
var exercise = [];
var index = 0;
exercise[index] = {
question: "Convert this binary number 01000001 to a decimal number:",
correctAnswer: "65",
answer: [ "127", "33", "42", "65" ]
};
index++;
exercise[index] = {
question: "How many combinations can you reach with 3 bits?",
correctAnswer: "8",
answer: [ "11", "9", "6", "8" ]
};
function random( from, to )
{
min = from > to ? to : from;
max = to < from ? from : to;
return( Math.floor( Math.random() * (max - min + 1 ) + min ) );
}
function showExercise( val )
{
document.getElementById( "question" ).innerHTML = exercise[val].question;
for( var i = 0; i < 4; i++ )
{
var index = random( 0, 3 - i );
console.log(index);
document.getElementsByTagName( "label" )[i].innerHTML = exercise[val].answer[index];
exercise[val].answer[index] = exercise[val].answer[3 - i];
}
}
randV = random( 0, index );
function validateInput()
{
var radio = document.getElementsByName( "choice" );
for( var i = 0; i < radio.length; i++ )
{
if( radio[i].checked )
{
if( exercise[randV].answer[i] == exercise[randV].correctAnswer[0] )
{
alert("Right");
}
else
{
alert( "Wrong" );
}
break;
}
}
}
showExercise( randV );
</script>
</body>
</html>
The problem in your code is that you are assigning possible answers in random order to the labels for the radio buttons but the index mapping that radio button to the answer it represents in your answer array is lost.
To fix this problem I have made a minimal change to your code to store the mapping in the value attribute of each radio button. Then when the user makes their selection and clicks CHECK the mapping is retrieved for the selected radio button and used to lookup the answer array.
<html>
<head>
<title>Quizgame</title>
</head>
<body>
<h1>Quizgame</h1>
<form>
<fieldset>
<legend id="question">Quizgame</legend>
<input type="radio" name="choice" id="1" value="1">
<label for="1">Placeholder</label><br>
<input type="radio" name="choice" id="2" value="2">
<label for="2">Placeholder</label><br>
<input type="radio" name="choice" id="3" value="3">
<label for="3">Placeholder</label><br>
<input type="radio" name="choice" id="4" value="4">
<label for="4">Placeholder</label><br>
<button onclick="validateInput()">Check</button>
</fieldset>
</form>
<script type="text/javascript">
var exercise = [];
var index = 0;
exercise[index] = {
question: "Convert this binary number 01000001 to a decimal number:",
correctAnswer: "65",
answer: [ "127", "33", "42", "65" ]
};
index++;
exercise[index] = {
question: "How many combinations can you reach with 3 bits?",
correctAnswer: "8",
answer: [ "11", "9", "6", "8" ]
};
function random( from, to )
{
min = from > to ? to : from;
max = to < from ? from : to;
return( Math.floor( Math.random() * (max - min + 1 ) + min ) );
}
function showExercise( val )
{
document.getElementById( "question" ).innerHTML = exercise[val].question;
for( var i = 0; i < 4; i++ )
{
var index = random( 0, 3 - i );
console.log(index);
document.getElementsByTagName( "label" )[i].innerHTML = exercise[val].answer[index];
//Store the original index to the answer option in the
//value attribute of the radio button.
document.getElementById((i+1).toString()).value = index.toString();
exercise[val].answer[index] = exercise[val].answer[3 - i];
}
}
randV = random( 0, index );
function validateInput()
{
var radio = document.getElementsByName( "choice" );
for( var i = 0; i < radio.length; i++ )
{
if( radio[i].checked )
{
//Retrieve the original index from the radio button
// and use it to look up the answer array.
var lOriginalIndex = document.getElementById((i+1).toString()).value;
if( exercise[randV].answer[lOriginalIndex] == exercise[randV].correctAnswer)
{
alert("Right");
}
else
{
alert( "Wrong" );
}
break;
}
}
}
showExercise( randV );
</script>
</body>
</html>

Categories

Resources