I have a short survey questions with answer YES/ NO
How can I get the total number of YES when submit button is clicked?
I will need to display certain images later according to the number of YES
<form>
<div class="field">
<label class="label">This is question number 1</label>
<div class="control">
<label class="radio">
<input type="radio" name="question1" value="1">
Yes
</label>
<label class="radio">
<input type="radio" name="question1" value="0">
No
</label>
</div>
</div>
<div class="field">
<label class="label">This is question number 2</label>
<div class="control">
<label class="radio">
<input type="radio" name="question2" value="1">
Yes
</label>
<label class="radio">
<input type="radio" name="question2" value="0">
No
</label>
</div>
</div>
<div class="field">
<label class="label">This is question number 3</label>
<div class="control">
<label class="radio">
<input type="radio" name="question3" value="1">
Yes
</label>
<label class="radio">
<input type="radio" name="question3" value="0">
No
</label>
</div>
</div>
<div class="field is-grouped">
<div class="control">
<div class="button is-link" onclick="countYes()">Submit</div>
</div>
<div class="control">
<button class="button is-link is-light">Cancel</button>
</div>
</div>
</form>
<script>
function countYes() {
totalVal = 0;
for(var y=0; y<3; y++)
{
var questionNo = document.getElementsByName("question" + y);
for (i=0; i<questionNo.length; i++)
{
if (document.forms.question[i].checked==true)
{
totalVal = totalVal + parseInt(document.forms.question[i].value);
console.log(totalVal);
}
}
}
}
</script>
I have a short survey questions with answer YES/ NO
How can I get the total number of YES when submit button is clicked?
I will need to display certain images later according to the number of YES
I currently have a bootstrap tab panel which consists of 3 tabs. Each tab has various number of checkboxes (I do not have control over this they are populated dynamically). What I am trying to achieve is to select the radio button with the id that matches my variable lets say 3. However, if the id does not match I always want to select the last check box.
This is what I have come up with so far.
var defaultSelection = 3;
if (defaultSelection) {
var radioOptions = document.querySelectorAll('[name="firstSet"], [name="secondSet"], [name="thirdSet"]');
for (var i = 0; i < radioOptions.length; i++)
{
if (radioOptions[i].id === defaultSelection)
{
document.querySelector("input[name=" + radioOptions[i].name + "][id=\'" + defaultSelection + "\']").checked = true;
} else {
//not entirly sure how to check the last item here in the particular tab
}
}
}
Markup looks like:
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="firstSet" id="1" value="1"> 1
</label>
<label class="radio-inline btn-sm">
<input type="radio" name="firstSet" id="2" value="2"> 2
</label>
<label class="radio-inline btn-sm radio-active">
<input type="radio" name="firstSet" id="3" value="3"> 3
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="4" value="4"> 4
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="5" value="5"> 5
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="secondSet" id="25" value="25"> 25
</label>
<label class="radio-inline">
<input type="radio" name="secondSet" id="27" value="27"> 27
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="thirdSetSet" id="55" value="55"> 55
</label>
</div>
The above works to check the radio with the id which matches my variable but I'm not entirely sure how to select the last option in a particular tab if none are select or match my variable entry.
Any pointers would be helpful.
One way you could go about this is by keeping track of whether the default radio button has been found and checked, and if that's not the case, then just check the last radio button.
Here's an example that implements this solution:
var defaultSelection = 3;
if (defaultSelection) {
var firstSet = document.querySelectorAll('[name="firstSet"]');
var secondSet = document.querySelectorAll('[name="secondSet"]');
var thirdSet = document.querySelectorAll('[name="thirdSet"]');
var tabs = [].concat(firstSet, secondSet, thirdSet);
tabs.forEach(function(tab) {
// keep track of whether default has been checked and
// grab the last radio button from the tab
var isDefaultChecked = false;
var lastRadioButton = tab[tab.length - 1];
for (var i = 0; i < tab.length; i++) {
var radio = tab[i];
var isDefaultSelection = parseInt(radio.id, 10) === 3;
// check the default radio button and
// set `isDefaultChecked` to true
if (isDefaultSelection) {
radio.checked = true;
isDefaultChecked = true;
}
}
// if no radio button was checked,
// check the last radio button
if (!isDefaultChecked) {
lastRadioButton.checked = true;
}
});
}
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="firstSet" id="1" value="1" /> 1
</label>
<label class="radio-inline btn-sm">
<input type="radio" name="firstSet" id="2" value="2" /> 2
</label>
<label class="radio-inline btn-sm radio-active">
<input type="radio" name="firstSet" id="3" value="3" /> 3
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="4" value="4" /> 4
</label>
<label class="radio-inline">
<input type="radio" name="firstSet" id="5" value="5" /> 5
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="secondSet" id="25" value="25" /> 25
</label>
<label class="radio-inline">
<input type="radio" name="secondSet" id="27" value="27" /> 27
</label>
</div>
<div class="d-flex flex-wrap">
<label class="radio-inline">
<input type="radio" name="thirdSet" id="55" value="55" /> 55
</label>
</div>
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.
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>
I am creating a simple quiz and would like to know how to show one question at a time but only using JavaScript. I do not know jQuery. Essentially, I would like the first question to be shown automatically.
Here is an example of what my HTML looks like:
<div id="q0">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" style="visibility:hidden">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" style="visibility:hidden">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
I currently don't have script for showing next div and hiding the previous one because I don't know how to even start.
I'm looking to have it put into this form...
function nextQ(){
// code
}
... and for it to be called by this button:
<button onclick="next()">Next Question</button>
I am really new to HTML and JavaScript and would appreciate any help.
Thanks.
Pure JavaScript version (config):
var showing = [1, 0, 0];
var questions = ['q0', 'q1', 'q2'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i < showing.length; i++) {
if (showing[i] == 1) {
qElems[i].style.display = 'none';
showing[i] = 0;
if (i == showing.length - 1) {
qElems[0].style.display = 'block';
showing[0] = 1;
} else {
qElems[i + 1].style.display = 'block';
showing[i + 1] = 1;
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()">Next Question</button>
Pure JavaScript version (no config):
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none;">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none;">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()">Next Question</button>
jQuery version:
$(function() {
$('.next').on('click', function() {
$('#questions>div').each(function() {
var id = $(this).index();
if ($(this).is(':visible')) {
$(this).hide();
if (id == $('#questions>div').length - 1) {
$('#questions>div').eq(0).show();
} else {
$('#questions>div').eq(id + 1).show();
}
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button class="next">Next Question</button>
Though I agree with #Bitwise on using jQuery instead on javascript alone to ensure cross-browser compatibility. But since you insist on using javascript, here's what you should do.
1) Ensure that your <li>'s are enclosed in a container tag first (say, <ul>) so you iterate only through desired list.
2) use display:none property instead of visibility:hidden. visibility:hidden simply hides an element, but it will still take up the same space as before. display:none hides an element, and it will not take up any space.
Here's the updated code.
HTML:
<ul id="listContainer">
<div id="q0">
<li style="display:list-item">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A"/>Green<br/>
<input type="radio" name="question0" value="B"/>Blue<br/>
<input type="radio" name="question0" value="C"/>Red<br/>
<input type="radio" name="question0" value="D"/>Purple<br/>
</li>
</div>
<div id="q1" >
<li style="display:none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A"/>Water<br/>
<input type="radio" name="question1" value="B"/>Cement<br/>
<input type="radio" name="question1" value="C"/>Trees<br/>
<input type="radio" name="question1" value="D"/>The Sky<br/>
</li>
</div>
<div id="q2" >
<li style="display:none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A"/>24<br/>
<input type="radio" name="question2" value="B"/>22<br/>
<input type="radio" name="question2" value="C"/>16<br/>
<input type="radio" name="question2" value="D"/>48<br/>
</li>
</div>
</ul>
<button id="next">next</button>
Javascript:
document.getElementById('next').addEventListener("click",function(){
var listContainer = document.getElementById("listContainer");
var listItem = listContainer.getElementsByTagName("li");
for (var i=0; i < listItem.length-1; i++)
{
if(listItem[i].style.display == "list-item")
{
listItem[i].style.display = "none";
listItem[i+1].style.display = "list-item";
break;
}
}
});
Here's the fiddle.
Cheers!
I would twist the code a little. Add question class to every div which acts as question i.e .question { display:none }. Add active class to first question (i.e. .active{display:block}, it shows the first question. Look for all divs with question class and add them to a variable, with every next button pressed,remove active class from current question add active class to next div with class question using classList.add and classList.remove of Javascript until last question is reached. Count keeps the current question's number.
I've done it in the codepen http://codepen.io/dwanirdesh/pen/EaQOPg
Or code directly from below:
<div id="q0" class="question active">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" class="question" >
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" class="question">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
<button onclick="next()">Next Question</button>
## CSS ##
.question{
display:none
}
.active{
display:block
}
## JAVASCRIPT ##
var questionNumber=0;
var questions=document.querySelectorAll('.question');
function next(){
questionNumber++;
if(questions.length>questionNumber)
{
document.querySelector('.active').classList.remove('active');
questions[questionNumber].classList.add('active');
}
}
Here is the java script function code. For this to work, you need to make sure that the div display property to be set as or in the html code. Also you need to name the id of the button to be "next" so that it can be hidden on reaching the last button.
function nextQ(){
var blockFound = 0;
var lastQuestion = 0;
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
if ( blockFound == 1){
blockFound = 0;
divs[i].style.display = 'block';
}else if ( divs[i].style.display == 'block' ){
if ( i + 2 == divs.length){
lastQuestion = 1;
}
blockFound = 1;
divs[i].style.display = 'none';
}
}
if ( lastQuestion == 1){
document.getElementById('next').style.visibility = 'hidden';
}
}
Html code here.
<div id="q0" style="display:block">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
</div>
<div id="q1" style="display:none">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
</div>
<div id="q2" style="display:none">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
</div>
<button id="next" onclick="nextQ()">Next Question</button>
Is it what you need?
<div id="q0">
<li>
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</li>
<button class="next" onclick="goNext(0)">Next Question</button>
</div>
<div id="q1" style="display:none">
<li>
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</li>
<button class="next" onclick="goNext(1)">Next Question</button>
</div>
<div id="q2" style="display:none">
<li>
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</li>
<button class="next" onclick="goNext(2)">Next Question</button>
</div>
<script language=javascript>
function goNext(i)
{
document.getElementById("q"+i).style.display = 'none';
i++;
document.getElementById("q"+i).style.display = 'block';
}
</script>