"Flashing" issue w/ jQuery .Show()/.Hide() - javascript

I'm making a trivia game for my school assignment and I swear I've done literally everything to solve the issue I'm experiencing. Essentially, without wasting too much of your time, I am using the jQuery methods of .show() and .hide() to transition between different phases of my game. However, whenever I prompt my game to start, via button on-click function, the screen will quickly "flash" of the content that's supposed to be showing up, and then reverts back to the "start" screen. I'm at wits end with this, and any help will truly be appreciated.
$(document).ready(function() {
//set up variables for game
var timer = 45;
var correctCount = 0;
var wrongCount = 0;
var endGame = false;
//capturing responses from user input
var question1Capture = $("input[name='question1']:checked").val();
var question2Capture = $("input[name='question2']:checked").val();
var question3Capture = $("input[name='question3']:checked").val();
var question4Capture = $("input[name='question4']:checked").val();
var question5Capture = $("input[name='question5']:checked").val();
var question6Capture = $("input[name='question6']:checked").val();
var question7Capture = $("input[name='question7']:checked").val();
var question8Capture = $("input[name='question8']:checked").val();
var question9Capture = $("input[name='question9']:checked").val();
var question10Capture = $("input[name='question10']:checked").val();
//!! If extra time, add audio queues here!!
// !!----------------
// setting timeout
setTimeout(timerCountDown, 1000 * 45);
//functions
function timerCountDown() {
timer--;
$("#timeLeft").text("Time Left: " + timer + " seconds");
if (timer === 0) {
endGame === true;
}
console.log(timer);
}
//function to start the game
function gameStart() {
$(".playScreen").show();
$(".bannerScreen").show();
$(".startScreen").hide();
$(".endScreen").hide();
timerCountDown();
}
//function for when the game ends
function gameOver() {
$(".playScreen").hide();
$(".bannerScreen").hide();
$(".startScreen").hide();
$(".endScreen").show();
}
//function to initialize the screen before the user presses the button
function initializeScreen () {
$(".playScreen").hide();
$(".bannerScreen").hide();
$(".endScreen").hide();
$(".startScreen").show();
}
//function for going through responses
function responseCheck() {
// question 1
if (question1Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 2
if (question2Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 3
if (question3Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 4
if (question4Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 5
if (question5Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 6
if (question6Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 7
if (question7Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 8
if (question8Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 9
if (question9Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
//question 10
if (question10Capture === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
}
}
//calling initializeScreen function
initializeScreen();
//start game click event
$("#startButton").on("click", function() {
gameStart();
responseCheck();
if (endGame) {
console.log("times up!")
gameOver();
}
});
//if the submit button is pressed before the time runs out
$("#submitButton").on("click", gameOver);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Poke-Trivia </title>
<!--Meta-Viewport tag-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--jQuery Link-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--javascript link-->
<script src="assets/javascript/app.js"></script>
<!--CSS link-->
<link href="assets/css/style.css" rel="stylesheet">
<!--Google Fonts link-->
<link href="https://fonts.googleapis.com/css?family=Oregano|Sedgwick+Ave" rel="stylesheet">
</head>
<body>
<h1> Pokemon Trivia </h1>
<form>
<!--START SCREEN BEGINS-->
<div class="startScreen">
<h2> Press the Pokeball to start! </h2>
<button id="startButton"></button>
</div>
<!--END OF START SCREEN-->
<h2 class="bannerScreen"> Answer 'em All ! </h2>
<h2 class="bannerScreen" id="timeLeft"> Time Left: 45 seconds </h3>
<!--START OF QUESTIONS-->
<div class="playScreen">
<p> Question 1: What is HM04 in GEN 1 (Red/Blue/Yellow)? </p>
<hr>
<div>
<input type="radio" name="question1" value="0" id="1A">
<label for="1A"> Cut </label>
<input type="radio" name="question1" value="0" id="1B">
<label for="1B"> Surf </label>
<input type="radio" name="question1" value="1" id="1C">
<label for="1C"> Strength </label>
<input type="radio" name="question1" value="0" id="1D">
<label for="1D"> Rock Smash </label>
</div>
<br>
<p> Question 2: Who is the Gym Leader of Fuschia City in GEN 2/4 (Silver/Gold/Diamond/Pearl/Platinum)?</p>
<hr>
<div>
<input type="radio" name="question2" value="0" id="2A">
<label for="2A"> Chuck </label>
<input type="radio" name="question2" value="0" id="2B">
<label for="2B"> Koga </label>
<input type="radio" name="question2" value="0" id="2C">
<label for="2C"> Whitney </label>
<input type="radio" name="question2" value="1" id="2D">
<label for="2D"> Janine </label>
</div>
<br>
<p> Question 3: Which Water-type Pokemon was a "Starter" for GEN 2/4 (Silver/Gold/Diamond/Pearl/Platinum)?</p>
<hr>
<div>
<input type="radio" name="question3" value="1" id="3A">
<label for="3A"> Totodile </label>
<input type="radio" name="question3" value="0" id="3B">
<label for="3B"> Oshawott </label>
<input type="radio" name="question3" value="0" id="3C">
<label for="3C"> Piplup </label>
<input type="radio" name="question3" value="0" id="3D">
<label for="3D"> Mudkip </label>
</div>
<br>
<p> Question 4: How many Legendary Pokemon were introduced in GEN 3 (Ruby/Sapphire/Emerald)?</p>
<hr>
<div>
<input type="radio" name="question4" value="0" id="4A">
<label for="4A"> 3 </label>
<input type="radio" name="question4" value="1" id="4B">
<label for="4B"> 8 </label>
<input type="radio" name="question4" value="0" id="4C">
<label for="4C"> 6 </label>
<input type="radio" name="question4" value="0" id="4D">
<label for="4D"> 2 </label>
</div>
<br>
<p> Question 5: In what region did GEN 6 (X/Y) take place?</p>
<hr>
<div>
<input type="radio" name="question5" value="0" id="5A">
<label for="5A"> Johto </label>
<input type="radio" name="question5" value="0" id="5B">
<label for="5B"> Unova </label>
<input type="radio" name="question5" value="1" id="5C">
<label for="5C"> Kalos </label>
<input type="radio" name="question5" value="0" id="5D">
<label for="5D"> Sinnoh </label>
</div>
<br>
<p> Question 6: In GEN 7 (Sun/Moon), what "notable" exclusion was present in the game, when compared to its predecessors?</p>
<hr>
<div>
<input type="radio" name="question6" value="1" id="6A">
<label for="6A"> Bicycles </label>
<input type="radio" name="question6" value="0" id="6B">
<label for="6B"> Rare Candies </label>
<input type="radio" name="question6" value="0" id="6C">
<label for="6C"> Pokemon Daycare </label>
<input type="radio" name="question6" value="0" id="6D">
<label for="6D"> A Rival </label>
</div>
<br>
<p> Question 7: In which year did the first ever Pokemon movie, featuring Mewtwo and Mew, release? </p>
<hr>
<div>
<input type="radio" name="question7" value="0" id="7A">
<label for="7A"> 1998 </label>
<input type="radio" name="question7" value="1" id="7B">
<label for="7B"> 1999 </label>
<input type="radio" name="question7" value="0" id="7C">
<label for="7C"> 2000 </label>
<input type="radio" name="question7" value="0" id="7D">
<label for="7D"> 2001 </label>
</div>
<br>
<p> Question 8: TRUE OR FALSE: Mark Hamill, of Star Wars fame, provided the voice of Entei in Pokemon 3: The Movie? </p>
<hr>
<div>
<input type="radio" name="question8" value="0" id="8A">
<label for="8A"> True </label>
<input type="radio" name="question8" value="1" id="8B">
<label for="8B"> False </label>
</div>
<br>
<p> Question 9: Is it possible to teach "Fly" to Scyther (Bug, Flying type)? </p>
<hr>
<div>
<input type="radio" name="question9" value="0" id="9A">
<label for="9A"> Yes, he does have wings after all. </label>
<input type="radio" name="question9" value="1" id="9B">
<label for="9B"> No, Game Freak hates him. </label>
</div>
<br>
<p> Question 10: How many current, potential evolutions are there for Evee? </p>
<hr>
<div>
<input type="radio" name="question10" value="0" id="10A">
<label for="10A"> 5 </label>
<input type="radio" name="question10" value="0" id="10B">
<label for="10B"> 6 </label>
<input type="radio" name="question10" value="0" id="10C">
<label for="10C"> 7 </label>
<input type="radio" name="question10" value="1" id="10D">
<label for="10D"> 8 </label>
</div>
<br>
<button id="submitButton" type="submit">Submit Answers</button>
</div>
<!-- End of Questions -->
<!-- Start of End Screen -->
<div class="endScreen">
<h2> Here are your results </h2>
<hr id="endScreenHr">
<h2 id="correctCountDiv"> Correct Answers: </h2>
<h2 id="wrongCountDiv"> Wrong Answers: </h2>
</div>
<!-- End of End Screen -->
</form>
</body>
</html>

Change button type from submit to button
<button id="submitButton" type="button">Submit Answers</button>

My resolution for this was to place event.preventDefault(); after my on click functions to prevent the form from naturally refreshing the page.

Related

Sum of Radio button values printed to the user

I'm very new to html.
I have a survey with two questions where the question choices are presented with radio buttons as this html code shows:
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
</form>
I want to print to the user the sum of his two selections.
So the output could be "You score is 10." if he answered yes to both questions etc.
How can I do this in the simplest way with the code being on the same page as the html code above? Is that possible?
var question1Answers = document.getElementsByName('q1');
var question2Answers = document.getElementsByName('q2');
var answer = 0;
question1Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
question2Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
console.log(answer);
please try this:
$("input[type='button']").click(function () {
var score = getChecklistItems();
alert("You score is : " + score);
});
function getChecklistItems() {
var total_score = 0
var result = $("input:radio:checked").get();
var checked_value = $.map(result, function (element) {
return $(element).attr("value");
});
for (i = 0; i < checked_value.length; i++) {
total_score += parseInt(checked_value[i])
}
return total_score
}
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
<p><input type="button" value="Submit"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery/JS Not Registering Radio Button Values Properly

I am working on a basic timed trivia game for my current school program, utilizing JavaScript and jQuery. As a simple overview, this trivia game employs 'radio buttons' to record user responses. Each button has a value of "1" ( for correct answer) or "0" (for wrong answer). However, no matter what I've tried or looked up, I have been unable to resolve my current problem: jQuery/JavaScript will either say all answers inputted are either all "correct" OR "wrong".
As you will see in my code, this problem is specific to my function responseCheck() and $("#submitButton").on("click", function() functions.
In my function responseCheck() function, my logic is that by using this $("input[type='radio']:checked").each(function() function, jQuery will go through all my the radio buttons that are checked; and then execute the following if/else statements:
if (parseInt($("input[type='radio']:checked").val()) === 1) : using this I am saying if the value of the button is equal to 1 (integer), then increment the correctCount variable.
else : using this I am saying if the value isn't equal to 1 (integer), then increment the wrongCount variable.
Obviously, there is some tangent i'm not connecting to my issue. I appreciate all help received. Thank you in advance.
PS
Ignore the commented out sections in my JS file, as they are bits of old/failed code
The top two variables in my JS file were my attempts to use arrays to catalog right/wrong answers but that didn't work for me. Feel free to ignore these as well.
I supplied my html file just for reference.
$(document).ready(function() {
//set up variables for game
//var responsesArray = [];
var correctAnswer = [1];
var wrongAnswer = [0];
//var buttonChecked = parseInt($("input[class='questions']:checked").val());
var timer = 46;
var timerInterval;
var correctCount = 0;
var wrongCount = 0;
var noDoubleDip = false;
//!! If extra time, add audio queues here!!
// !!---------------
//functions
function timerCountDown() {
timer--;
if (timer > 0) {
$("#timeLeft").text("Time Left: " + timer + " seconds");
console.log(timer);
}
else {
gameOver("fail");
}
}
//function for when the game ends
function gameOver(status) {
clearInterval(timerInterval);
if(status == 'success') {
alert('You Did It');
}
else {
alert('Time Ran Out');
}
console.log("times up!")
$(".playScreen").hide();
$(".bannerScreen").hide();
$(".startScreen").hide();
$(".endScreen").show();
console.log("game's over!");
}
//function for going through responses; issue: COUNTS ALL FOR ONE <--- UNRESOLVED
function responseCheck() {
// responsesArray.push(buttonChecked);
$("input[type='radio']:checked").each(function() {
//debugger;
if (parseInt($("input[type='radio']:checked").val()) === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("wrong Answers: " + wrongCount);
}
});
// BELOW DID WORK BUT RAN THROUGH EACH question AT THE SAME TIME
// // question 1
// if (parseInt($("input[name='question1']:checked").val()) === 1) {
// console.log("correct");
// correctCount++;
// $("#correctCountDiv").text("Correct Answers: " + correctCount);
// }
// else {
// console.log("incorrect");
// wrongCount++;
// $("#wrongCountDiv").text("Wrong Answers: " + wrongCount);
// }
}
//start game click event
$("#startButton").on("click", function() {
event.preventDefault();
$(".playScreen").show();
$(".bannerScreen").show();
$(".startScreen").hide();
$(".endScreen").hide();
timerInterval = setInterval(timerCountDown, 1000);
});
//on click attempt to record user presses in quiz
// $("#submitButton").on("click", function() {
// if (noDoubleDip) {
//
// // event.preventDefault();
// //
// // attempt to prevent additional clicks from counting towards appropiate category -- UNRESOLVED <--
//
// // above code actually stopped another button from being pressed
//
// correctCount = "";
//
// wrongCount = "";
//
// }
//
// noDoubleDip = true;
// });
//if the submit button is pressed before the time runs out
$("#submitButton").on("click", function() {
event.preventDefault();
responseCheck();
console.log("Finished before timer ran out");
gameOver("success");
});
// $("input").on("click", function() {
//
// if (correctAnswer[0]) {
//
// console.log("Correct Input Received");
//
// }
//
// else {
//
// console.log("Incorrect Input Received");
// }
//
// });
});
<!DOCTYPE html>
<html>
<head>
<title> Poke-Trivia </title>
<!--Meta-Viewport tag-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--jQuery Link-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--javascript link-->
<script src="assets/javascript/app.js"></script>
<!--CSS link-->
<link href="assets/css/style.css" rel="stylesheet">
<!--Google Fonts link-->
<link href="https://fonts.googleapis.com/css?family=Oregano|Sedgwick+Ave" rel="stylesheet">
</head>
<body>
<h1> Pokemon Trivia </h1>
<form>
<!--START SCREEN BEGINS-->
<div class="startScreen">
<h2> Press the Pokeball to start! </h2>
<button id="startButton"></button>
</div>
<!--END OF START SCREEN-->
<h2 class="bannerScreen"> Answer 'em All </h2>
<h2 class="bannerScreen" id="timeLeft"> Time Left: 45 seconds </h3>
<!--START OF QUESTIONS-->
<div class="playScreen">
<p> Question 1: What is HM04 in GEN 1 (Red/Blue/Yellow)? </p>
<hr>
<div>
<input type="radio" class="questions" name="question1" value="0" id="1A">
<label for="1A"> Cut </label>
<input type="radio" class="questions" name="question1" value="0" id="1B">
<label for="1B"> Surf </label>
<input type="radio" class="questions" name="question1" value="1" id="1C">
<label for="1C"> Strength </label>
<input type="radio" class="questions" name="question1" value="0" id="1D">
<label for="1D"> Rock Smash </label>
</div>
<br>
<p> Question 2: Who is the Gym Leader of Fuschia City in GEN 2/4 (Silver/Gold/Diamond/Pearl/Platinum)?</p>
<hr>
<div>
<input type="radio" class="questions" name="question2" value="0" id="2A">
<label for="2A"> Chuck </label>
<input type="radio" class="questions" name="question2" value="0" id="2B">
<label for="2B"> Koga </label>
<input type="radio" class="questions" name="question2" value="0" id="2C">
<label for="2C"> Whitney </label>
<input type="radio" class="questions" name="question2" value="1" id="2D">
<label for="2D"> Janine </label>
</div>
<br>
<p> Question 3: Which Water-type Pokemon was a "Starter" for GEN 2/4 (Silver/Gold/Diamond/Pearl/Platinum)?</p>
<hr>
<div>
<input type="radio" class="questions" name="question3" value="1" id="3A">
<label for="3A"> Totodile </label>
<input type="radio" class="questions" name="question3" value="0" id="3B">
<label for="3B"> Oshawott </label>
<input type="radio" class="questions" name="question3" value="0" id="3C">
<label for="3C"> Piplup </label>
<input type="radio" class="questions" name="question3" value="0" id="3D">
<label for="3D"> Mudkip </label>
</div>
<br>
<p> Question 4: How many Legendary Pokemon were introduced in GEN 3 (Ruby/Sapphire/Emerald)?</p>
<hr>
<div>
<input type="radio" class="questions" name="question4" value="0" id="4A">
<label for="4A"> 3 </label>
<input type="radio" class="questions" name="question4" value="1" id="4B">
<label for="4B"> 8 </label>
<input type="radio" class="questions" name="question4" value="0" id="4C">
<label for="4C"> 6 </label>
<input type="radio" class="questions" name="question4" value="0" id="4D">
<label for="4D"> 2 </label>
</div>
<br>
<p> Question 5: In what region did GEN 6 (X/Y) take place?</p>
<hr>
<div>
<input type="radio" class="questions" name="question5" value="0" id="5A">
<label for="5A"> Johto </label>
<input type="radio" class="questions" name="question5" value="0" id="5B">
<label for="5B"> Unova </label>
<input type="radio" class="questions" name="question5" value="1" id="5C">
<label for="5C"> Kalos </label>
<input type="radio" class="questions" name="question5" value="0" id="5D">
<label for="5D"> Sinnoh </label>
</div>
<br>
<p> Question 6: In GEN 7 (Sun/Moon), what "notable" exclusion was present in the game, when compared to its predecessors?</p>
<hr>
<div>
<input type="radio" class="questions" name="question6" value="1" id="6A">
<label for="6A"> Bicycles </label>
<input type="radio" class="questions" name="question6" value="0" id="6B">
<label for="6B"> Rare Candies </label>
<input type="radio" class="questions" name="question6" value="0" id="6C">
<label for="6C"> Pokemon Daycare </label>
<input type="radio" class="questions" name="question6" value="0" id="6D">
<label for="6D"> A Rival </label>
</div>
<br>
<p> Question 7: In which year did the first ever Pokemon movie, featuring Mewtwo and Mew, release? </p>
<hr>
<div>
<input type="radio" class="questions" name="question7" value="0" id="7A">
<label for="7A"> 1998 </label>
<input type="radio" class="questions" name="question7" value="1" id="7B">
<label for="7B"> 1999 </label>
<input type="radio" class="questions" name="question7" value="0" id="7C">
<label for="7C"> 2000 </label>
<input type="radio" class="questions" name="question7" value="0" id="7D">
<label for="7D"> 2001 </label>
</div>
<br>
<p> Question 8: TRUE OR FALSE: Mark Hamill, of Star Wars fame, provided the voice of Entei in Pokemon 3: The Movie? </p>
<hr>
<div>
<input type="radio" class="questions" name="question8" value="0" id="8A">
<label for="8A"> True </label>
<input type="radio" class="questions" name="question8" value="1" id="8B">
<label for="8B"> False </label>
</div>
<br>
<p> Question 9: Is it possible to teach "Fly" to Scyther (Bug, Flying type)? </p>
<hr>
<div>
<input type="radio" class="questions" name="question9" value="0" id="9A">
<label for="9A"> Yes, he does have wings after all. </label>
<input type="radio" class="questions" name="question9" value="1" id="9B">
<label for="9B"> No, Game Freak hates him. </label>
</div>
<br>
<p> Question 10: How many current, potential evolutions are there for Evee? </p>
<hr>
<div>
<input type="radio" class="questions" name="question10" value="0" id="10A">
<label for="10A"> 5 </label>
<input type="radio" class="questions" name="question10" value="0" id="10B">
<label for="10B"> 6 </label>
<input type="radio" class="questions" name="question10" value="0" id="10C">
<label for="10C"> 7 </label>
<input type="radio" class="questions" name="question10" value="1" id="10D">
<label for="10D"> 8 </label>
</div>
<br>
<button id="submitButton" type="submit">Submit Answers</button>
</div>
<!-- End of Questions -->
<!-- Start of End Screen -->
<div class="endScreen">
<h2> Here are your results </h2>
<hr id="endScreenHr">
<h2 id="correctCountDiv"> Correct Answers: 0</h2>
<h2 id="wrongCountDiv"> Wrong Answers: 0</h2>
</div>
<!-- End of End Screen -->
</form>
</body>
</html>
JQuery's .each() is already providing you with each element per iteration as the keyword $(this), by you using $(parseInt($('input[type="radio"]:checked').val()) === 1) you are grabbing every element that is a radio button and checked, so .val() is giving you the value of the first element in the collection on each iteration, change your function to the following:
$("input[type='radio']:checked").each(function() {
//if (parseInt($("input[type='radio']:checked").val()) === 1) { //NO
if (parseInt($(this).val()) === 1) { //Check the .val() of the current radio button
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("wrong Answers: " + wrongCount);
}
});
Here is a working version of your responseCheck():
$("input[type='radio']:checked").each(function(i, e) {
//debugger;
if (parseInt($(e).val()) === 1) {
console.log("correct");
correctCount++;
$("#correctCountDiv").text("Correct Answers: " + correctCount);
}
else {
console.log("incorrect");
wrongCount++;
$("#wrongCountDiv").text("wrong Answers: " + wrongCount);
}
});

issue with if/else conditions with radio elements

I'm not good with Javascript and I'm trying to build a two-question quiz based on yes-no answers. When I look at the console I see the yes-no values if I do console.log(answer1 + answer3); But the alert doesn't work. If I remove .checked and do equal to true/false the first alert works.
Any help would be appreciated
var answer1 = document.getElementById('q1').value;
var answer2 = document.getElementById('q2').value;
var answer3 = document.getElementById('q3').value;
var answer4 = document.getElementById('q4').value;
if (answer1.checked && answer3.checked) {
alert('walking park');
}
else if (answer1.checked && answer4.checked) {
alert('no walk in park');
}
else if (answer2.checked && answer4.checked ) {
alert('oh noooo!');
}
else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button type="button" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>
Use checked == true or simply checked and remove .value
answer1 = document.getElementById('q1');
answer2 = document.getElementById('q2');
answer3 = document.getElementById('q3');
answer4 = document.getElementById('q4');
function checkanswear(event){
event.preventDefault()
if (answer1.checked && answer3.checked) {
alert('walking park');
}
else if (answer1.checked&& answer4.checked) {
alert('no walk in park');
}
else if (answer2.checked && answer4.checked ) {
alert('oh noooo!');
}
else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
}
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button onclick="checkanswear(event)" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>
The problem is that the .value of your checkboxes is the string "yes" or "no". Strings don't have a checked attribute.
Solution: Just remove the .value part. Let answer1, answer2, etc be the input elements themselves. Then you can use .checked on them.
Example:
document.getElementById('myBtn').onclick = function() {
var answer1 = document.getElementById('q1');
var answer2 = document.getElementById('q2');
var answer3 = document.getElementById('q3');
var answer4 = document.getElementById('q4');
if (answer1.checked && answer3.checked) {
alert('walking park');
} else if (answer1.checked && answer4.checked) {
alert('no walk in park');
} else if (answer2.checked && answer4.checked) {
alert('oh noooo!');
} else if (answer2.checked && answer3.checked) {
alert('cor blimey gov!');
}
};
<form>
<p>Question 1</p>
<fieldset>
<label for="Question1">Can your dog eat food?</label>
<input type="radio" id="q1" name="question1" value="yes"> Yes<br>
<input type="radio" id="q2" name="question1" value="no"> No
</fieldset>
<p>Question 2</p>
<fieldset>
<label for="Question2">Can your dog run in the park</label>
<input type="radio" id="q3" name="question2" value="yes"> Yes<br>
<input type="radio" id="q4" name="question2" value="no"> No
</fieldset>
<button type="button" id="myBtn" class="btn btn-med btn-brand-one">submit</button>
</form>

onClick is not reacting in quiz

I'm doing this project for school with a quiz in JavaScript. After clicking the button I want it to show a message but for some reason after clicking nothing happens. Could you guys help me? I went through it few times and still don't know what's wrong;/
function check() {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var question4 = document.quiz.question4.value;
var question5 = document.quiz.question5.value;
var question6 = document.quiz.question6.value;
var question7 = document.quiz.question7.value;
var question8 = document.quiz.question8.value;
var correct = 0;
if (question1 == "voldoende" || "goed") {
correct++;
}
if (question2 == "Voldoende" || "Goed") {
correct++;
}
if (question3 == "Voldoende" || "Goed") {
correct++;
}
if (question4 == "Voldoende" || "Goed") {
correct++;
}
if (question5 == "Voldoende" || "Goed") {
correct++;
}
if (question6 == "Voldoende" || "Goed") {
correct++;
}
if (question7 == "Voldoende" || "Goed") {
correct++;
}
if (question8 == "Voldoende" || "Goed") {
correct++;
}
var messages = ["You passed!", "You failed", "You did awesome"];
var range;
if (correct < 5) {
range = 1;
}
if (correct > 5 && correct < 8) {
range = 0;
}
if (correct == 8) {
range = 2;
}
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = messages[range];
}
body {
font-family: 'Lato', sans-serif;
}
after_submit {
visibility: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/stylesheets.css"> </head>
<body>
<h1>Will I get a good grade for this project?</h1>
<form id="quiz" name="quiz">
<p>Is my code interactief?</p>
<input id="mc" type="radio" name="Question1" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question1" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question1" value="goed">Goed
<br>
<p>Dom Manipulatie</p>
<input id="mc" type="radio" name="Question2" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question2" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question2" value="goed">Goed
<br>
<p>Controle Structuren</p>
<input id="mc" type="radio" name="Question3" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question3" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question3" value="goed">Goed
<br>
<p>Loops</p>
<input id="mc" type="radio" name="Question4" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question4" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question4" value="goed">Goed
<br>
<p>Array/object</p>
<input id="mc" type="radio" name="Question5" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question5" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question5" value="goed">Goed
<br>
<p>Functies</p>
<input id="mc" type="radio" name="Question6" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question6" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question6" value="goed">Goed
<br>
<p>Flow</p>
<input id="mc" type="radio" name="Question7" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question7" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question7" value="goed">Goed
<br>
<p>Kwaliteit</p>
<input id="mc" type="radio" name="Question8" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question8" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question8" value="goed">Goed
<br>
<input id="button" type="button" value="Check my grade" onclick="check();"> </form>
<div id="after_submit">
<p id="message"></p>
<p id="number_correct"></p>
</div>
<script src="js/game.js"></script>
</body>
</html>
You need to change all your question1.value question2.value... to Question1.value Question2.value ... since that's the name of your inputs
But you still need to check your logic because no matter which choice you select on your radio buttons, you always get the message "You did awesome"
Press F12 to see Developer tools. In the Console, you'll see error messages like this:
Uncaught TypeError: Cannot read property 'value' of undefined
That means that document.quiz.question1, ... are not defined. Why? Because properties names are wrong. Write (note the uppercase character):
document.quiz.Question1
I've spotted MANY ERRORS in your code (Either programmaticly or
logically) 1. Goed is not the same with goed, so as
Voldoende and voldoende (Consider consistency of case whether it's HTML or Javascript. Yes, HTML is not a Case-sensitive language
but Javascript do. 2. 5 points shows undefined -> must use
correct <= 5 condition 3. Logical Operation Related Concern
-> question1 == "voldoende" is not the same as "voldoende" (Solution: still rewrite question1 == value on the right side of or
operator) -> this is also the main reason why you always get 8 points. (Right side of the or operator is ALWAYS TRUE, you're just restating that "goed" == "goed" if you don't include the questionN == code)
Lastly #Jérémie L's statement, F12 Developer tools which he have
used, is basically the thing to use to address such problems :) It
helps alot. Use breakpoints to know the value of each line / blocks
of codes.
Snippet below contains correct script of your project.
I've put comment tags on the changes for readability
function check() {
<!-- question1 to Question1, right side of assignment operator -> due to case sensitivity, must be first letters capitalized in both JS and HTML -->
var question1 = document.quiz.Question1.value;
var question2 = document.quiz.Question2.value;
var question3 = document.quiz.Question3.value;
var question4 = document.quiz.Question4.value;
var question5 = document.quiz.Question5.value;
var question6 = document.quiz.Question6.value;
var question7 = document.quiz.Question7.value;
var question8 = document.quiz.Question8.value;
var correct = 0;
<!-- goed on the right side of logical operator must contain question1 == on its left, always remember -->
if (question1 == "voldoende" || question1 == "goed") {
correct++;
}
if (question2 == "voldoende" || question2 == "goed") {
correct++;
}
if (question3 == "voldoende" || question3 == "goed") {
correct++;
}
if (question4 == "voldoende" || question4 == "goed") {
correct++;
}
if (question5 == "voldoende" || question5 == "goed") {
correct++;
}
if (question6 == "voldoende" || question6 == "goed") {
correct++;
}
if (question7 == "voldoende" || question7 == "goed") {
correct++;
}
if (question8 == "voldoende" || question8 == "goed") {
correct++;
}
var messages = ["You passed!", "You failed", "You did awesome"];
var range;
<!-- correct < 5 to correct <= 5, making no space for undefined message -->
if (correct <= 5) {
range = 1;
}
if (correct > 5 && correct < 8) {
range = 0;
}
if (correct == 8) {
range = 2;
}
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = messages[range];
}
body {
font-family: 'Lato', sans-serif;
}
after_submit {
visibility: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/stylesheets.css"> </head>
<body>
<h1>Will I get a good grade for this project?</h1>
<form id="quiz" name="quiz">
<p>Is my code interactief?</p>
<input id="mc" type="radio" name="Question1" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question1" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question1" value="goed">Goed
<br>
<p>Dom Manipulatie</p>
<input id="mc" type="radio" name="Question2" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question2" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question2" value="goed">Goed
<br>
<p>Controle Structuren</p>
<input id="mc" type="radio" name="Question3" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question3" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question3" value="goed">Goed
<br>
<p>Loops</p>
<input id="mc" type="radio" name="Question4" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question4" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question4" value="goed">Goed
<br>
<p>Array/object</p>
<input id="mc" type="radio" name="Question5" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question5" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question5" value="goed">Goed
<br>
<p>Functies</p>
<input id="mc" type="radio" name="Question6" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question6" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question6" value="goed">Goed
<br>
<p>Flow</p>
<input id="mc" type="radio" name="Question7" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question7" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question7" value="goed">Goed
<br>
<p>Kwaliteit</p>
<input id="mc" type="radio" name="Question8" value="genant">Genant
<br>
<input id="mc" type="radio" name="Question8" value="voldoende">Voldoende
<br>
<input id="mc" type="radio" name="Question8" value="goed">Goed
<br>
<input id="button" type="button" value="Check my grade" onclick="check();"> </form>
<div id="after_submit">
<p id="message"></p>
<p id="number_correct"></p>
</div>
<script src="js/game.js"></script>
</body>
</html>

JavaScript quiz answer check up

I'm trying to make a score base quiz where it shows how much score you get when finished e.g. out of 8 and the answers you got incorrect. I have the score system out of the way, just not the validation
HTML
<div class="quiz">
1) What noise does a dog make?</div>
<div class="values">
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">a) Cluck<br>
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">b) Meow<br>
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">c) Moo<br>
<input type="radio" value="1" id="q1" name="q1" onclick="question('jq1',this.value)">d) Woof</div><br>
<input type="hidden" name="jq1" id="jq1" />
<div class="quiz">
2) What noise does a cat make?</div>
<div class="values">
<input type="radio" value="1" id="q2" name="q2" onclick="question('jq2',this.value)">a) Meow<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">b) Cluck<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">c) Woof<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">d) Moo</div><br>
<input type="hidden" name="jq2" id="jq2" />
(sorry for inappropriate questions, they're just there as placeholders :D)
JavaScript
function question(ref,val) {
var x = document.getElementById(ref);
x.value = val;
}
function result() {
var score = 0;
var x = document.getElementById('jq1');
score = eval (score) + eval(x.value);
var x = document.getElementById('jq2');
score = eval (score) + eval(x.value);
alert("You scored: "+score +" out of 2!");
}
I'd like a new line underneath the current one in the alert box saying "Questions 1, 2, 3 were incorrect". Just very unsure on how to do this and would like someone's help.
Thanks very much!
A more object oriented answer
DEMO: http://jsfiddle.net/Victornpb/3cwzndp8/1/
var q = [
{
question:"What noise does a dog make?",
options:["Meow", "Cluck","Woof","Moo"],
answers: [0,0,1,0]
},
{
question:"What noise does a cat make?",
options:["Meow", "Cluck","Woof","Moo"],
answers: [1,0,0,0]
}
];
var questionary = generateQuestionary(q);
quizBody.appendChild(questionary);
function generateQuestionary(obj){
var questionary = tag("div",{className:"questionary"});
for(var i=0; i<obj.length; i++){
questionary.appendChild(generateQuestionHtml(obj[i], i));
}
return questionary;
}
function generateQuestionHtml(obj, n){
var answers = tag("div",{className:"answers"});
for(var i=0; i<obj.options.length; i++){
answers.appendChild(
tag("label",{},
tag("input",{type:"radio", name:"q"+n, value:obj.answers[i],onclick:ck} ),
tag("span",{}, obj.options[i]),
tag("br")
)
);
}
return tag("div",{className:"quiz"},
tag("div",{className:"question"}, obj.question),
answers,
tag("div",{className:"info"})
);
}
function ck(e){
console.log(this);
var infoBox = this.parentElement.parentElement.parentElement.getElementsByClassName("info")[0];
if(this.value==1){
infoBox.innerHTML = "Correct!";
infoBox.classList.remove("wrong");
}
else{
infoBox.innerHTML = "Incorrect answer :(";
infoBox.classList.add("wrong");
}
}
I used a utility function to generate the DOM Elements (the tag() function)
https://gist.github.com/victornpb/11201998
Assuming you want a rudimentary, client-side system, I would suggest declaring an object that holds the answers when the page loads, with the name of each group of choices as the key, and the correct answers being the values.
Say that question 1, labeled "q1", has 3 choices, the answer being the first.
var answers = {q1:0, q2:3};
//The key "q1" gets the value 0, while "q2" will get 3 (or any arbitrary value you want)
Now you can say
if(answers["q1"] != document.forms["formNameHere"].elements["q1"].value)
alert("Everything is awful, you got question one wrong");
You can iterate through each question, checking if the answer is correct, and assembling a string of the wrong answers, which you can display through your alert on a new line.
It's not clear what you want to accomplish.
eval is totally unnecessary here, and shouldn't be used.
window.onload = function() {
check.onclick = result;
}
function result() {
var score = 0;
score += parseInt(getSelectedRadioValue("q1")) || 0;
score += parseInt(getSelectedRadioValue("q2")) || 0;
alert("You scored: " + score + " out of 2!");
}
function getSelectedRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
}
<div class="quiz">
1) What noise does a dog make?</div>
<div class="answers">
<label>
<input type="radio" value="0" name="q1">a) Meow</label>
<br>
<label>
<input type="radio" value="0" name="q1">b) Cluck</label>
<br>
<label>
<input type="radio" value="1" name="q1">c) Woof</label>
<br>
<label>
<input type="radio" value="0" name="q1">d) Moo</label>
<br>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />
<div class="quiz">
2) What noise does a cat make?</div>
<div class="answers">
<label>
<input type="radio" value="1" name="q2">a) Meow</label>
<br>
<label>
<input type="radio" value="0" name="q2">b) Cluck</label>
<br>
<label>
<input type="radio" value="0" name="q2">c) Woof</label>
<br>
<label>
<input type="radio" value="0" name="q2">d) Moo</label>
<br>
</div>
<br>
<input type="hidden" name="jq2" id="jq2" />
<input type="button" id="check" value="I'm done">
Demo:
https://quiz-using-javascript.web.app/
Source Code:
https://github.com/mhsunny/JavaScript-Quiz
This is the project to build a quiz using JavaScript. You can find how to check the answer of questions using javascript forEach() and using setInterval and clearInteval method.
app.js
app.js
const correctAnswers = ['B', 'B', 'B', 'B'];
const form = document.querySelector('.quiz-form');
const result = document.querySelector('.result');
form.addEventListener('submit', e =>{
e.preventDefault();
let score = 0;
const userAnswer = [form.q1.value, form.q2.value, form.q3.value, form.q4.value]
//check answers
userAnswer.forEach((answer, index) =>{
if(answer === correctAnswers[index]){
score +=25;
}
// console.log(score);
//show result on page
});
scrollTo(0, 0);
result.classList.remove('d-none');
let output = 0;
const timer = setInterval(()=>{
result.querySelector('span').textContent = `${output}%`;
if(output === score){
clearInterval(timer);
}else{
output++;
}
}, 10)
})
// let i = 0;
// const timer = setInterval(()=>{
// console.log("hello")
// i++;
// if(i == 5){
// clearInterval(timer);
// }
// }, 1000)
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> JavaScript Quiz</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<!-- top section -->
<div class="intro py-3 bg-white text-center">
<div class="container">
<h2 class="text-primary display-3 my-4"> Quiz using Javascript</h2>
</div>
</div>
<!-- result section -->
<div class="result py-4 d-none bg-light text-center">
<div class="container lead">
<p>You are <span class="text-primary display-4 p-3">0%</span> ninja</p>
</div>
</div>
<!-- quiz section -->
<div class="quiz py-4 bg-primary">
<div class="container">
<h2 class="my-5 text-white">On with the questions...</h2>
<form class="quiz-form text-light">
<div class="my-5">
<p class="lead font-weight-normal">1. How do you give a ninja directions?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q1" value="A" checked>
<label class="form-check-label">Show them a map</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q1" value="B">
<label class="form-check-label">Don't worry, the ninja will find you</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">2. If a ninja has 3 apples, then gives one to Mario & one to Yoshi, how many apples does the ninja have left?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q2" value="A" checked>
<label class="form-check-label">1 apple</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q2" value="B">
<label class="form-check-label">3 apples, and two corpses</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">3. How do you know when you've met a ninja?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q3" value="A" checked>
<label class="form-check-label">You'll recognize the outfit</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q3" value="B">
<label class="form-check-label">The grim reaper will tell you</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">4. What's a ninja's favourite array method?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q4" value="A" checked>
<label class="form-check-label">forEach()</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q4" value="B">
<label class="form-check-label">slice()</label>
</div>
</div>
<div class="text-center">
<input type="submit" class="btn btn-light">
</div>
</form>
</div>
</div>
<script src="app.js"></script>
</body>
</html>

Categories

Resources