Show Questions One At a Time in Quiz Website in HTML

show questions one at a time in quiz website in html

Here I've made an example of how you can realize this solution. You will need 3 files.

1) Download jquery library and put it in site root folder, in this example I use jquery-3.3.1.min.js

2) Create file index.php with this content

<html>
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="services">
<div id="container"></div>
</div>

<script>
$(document).ready(function(){
$('body').on('click','#next', function(){
var curr_id = $(this).data('nextQuestion');
var answer1 = $('#radio1').is(':checked');
var answer2 = $('#radio2').is(':checked');
var answer3 = $('#radio3').is(':checked');
var answer4 = $('#radio4').is(':checked');
getQuestion(curr_id, answer1, answer2, answer3, answer4);
});

function getQuestion(curr_id, answer1=false, answer2=false, answer3=false, answer4=false){
$.post("ajax.php",
{
next_id: parseInt(curr_id)+1,
answer1: answer1,
answer2: answer2,
answer3: answer3,
answer4: answer4,
},
function(data, status){
$('#container').html(data);
});
}

getQuestion(-1);
});

</script>

</body>
</html>

2) Create ajax.php

<?php
$con=mysqli_connect("localhost","root","","quiz"); // change here to your data
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Check the number of all questions, if next_id is more than last question, back to first or whatever you want;
$response=mysqli_query($con,"select * from questions");
$number_of_all_questions = mysqli_num_rows($response);

if($number_of_all_questions <= $_POST['next_id']){
$_POST['next_id'] = 0;
}

// query next question

$response=mysqli_query($con,"select * from questions WHERE id =(select min(id) from questions where id > {$_POST['next_id']})");
?>

<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>

<div id="question_<?= $result['id'] ?>" class='question'> <!--check the class for plurals if error occurs-->
<h2><?= $result['id'].".".$result['question_name'] ?></h2>
<div class='align'>
<input type="radio" value="1" id='radio1' name='1'>
<label id='ans1' for='1'><?= $result['answer1'] ?></label>
<br/>
<input type="radio" value="2" id='radio2' name='2'>
<label id='ans2' for='2'><?= $result['answer2'] ?></label>
<br/>
<input type="radio" value="3" id='radio3' name='3'>
<label id='ans3' for='3'><?= $result['answer3'] ?></label>
<br/>
<input type="radio" value="4" id='radio4' name='4'>
<label id='ans4' for='4'><?= $result['answer4'] ?></label>
</div>
<br/>
<input type="button" data-next-question="<?= $_POST['next_id'] ?>" id='next' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
<?php mysqli_close($con); ?>

How to make quiz questions appear one at a time after clicking next in Javascript?

You will need to render the HTML content of the question each time the index is updated, so you should throw the rendering logic into a function and call it each time you increment the question.

Also, if you know you are on the last question, you can change the text of the next button to "Finish" or render a different button in its place.

Lastly, you will want to clean-up any event listeners you associated to the DOM before replacing the content or you will have memory leaks.

const quizEl = document.querySelector('.quiz');
const questions = [{
name: 'How many inches in a foot?', answer: '2',
options: [{ title: '3' }, { title: '6' }, { title: '12' }, { title: '36' } ]
}, {
name: 'How tall is the Eiffel Tower?', answer: '1',
options: [{ title: '308m' }, { title: '324m' }, { title: '352m' }, { title: '463m' } ]
}];
let currentQuestion = 0;
let submitted = false;

const renderQuestion = () => {
submitted = false;

// Clean-up since we are removing the DOM
removeClickListener(quizEl.querySelector('#nextQuestion'), handleNext);
removeClickListener(quizEl.querySelector('#submit'), handleSubmit);

const question = questions[currentQuestion];
const isLast = currentQuestion === questions.length - 1;

quizEl.innerHTML = `
<h1>${question.name}</h1>
<form id="myForm">
<input type="radio" id="0" name="option" value="0">
<label for="0">${question.options[0].title}</label><br>

<input type="radio" id="1" name="option" value="1">
<label for="1">${question.options[1].title}</label><br>

<input type="radio" id="2" name="option" value="2">
<label for="2">${question.options[2].title}</label><br>

<input type="radio" id="3" name="option" value="3">
<label for="3">${question.options[3].title}</label><br>

<p id="message"></p>

<button id="submit">Submit</button>
<button id="nextQuestion">${!isLast ? 'Next' : 'Finish'}</button>
</form>
`;

// Re-associate the listener
addClickListener(quizEl.querySelector('#nextQuestion'), handleNext);
addClickListener(quizEl.querySelector('#submit'), handleSubmit);
}

const addClickListener = (btn, listener) => {
if (btn) btn.addEventListener('click', listener);
};

const removeClickListener = (btn, listener) => {
if (btn) btn.removeEventListener('click', listener);
};

const handleNext = e => {
e.preventDefault();

const msg = document.getElementById('message');

if (document.querySelector('input[name="option"]:checked') === null) {
msg.innerHTML = "Select an answer to proceed."
return; // Exit from function.
}

if (!submitted) {
msg.innerHTML = "Please submit your answer before proceeding."
return; // Exit from function.
}

if (currentQuestion < questions.length - 1) {
currentQuestion++;
renderQuestion();
} else {
alert("You've reached the last question.");
}
};

const handleSubmit = e => {
e.preventDefault()

const msg = document.getElementById('message');
const ans = document.querySelector('input[name="option"]:checked');

if (!ans) {
msg.innerHTML = "Please select an answer."
return; // Exit from function.
}

const question = questions[currentQuestion];
const correctAns = question.answer;
const userAns = ans.value;

if (correctAns === userAns) {
msg.innerHTML = "Correct"
} else {
msg.innerHTML = "Incorrect"
}

document.getElementById("0").disabled = true;
document.getElementById("1").disabled = true;
document.getElementById("2").disabled = true;
document.getElementById("3").disabled = true;

submitted = true;
};

renderQuestion();
#message { color: red; }
<div class="quiz"></div>

Displaying one quiz item at a time

This is how you can achieve what you want without changing your code too much.

var myQuiz = [    {    ques: "What is the capital of California?",    choices: ["Los Angeles", "San Francisco", "Sacramento", "San Diego", "Oakland"],    correctAnswer: "Sacramento"    },     {    ques: "What is the capital of Pennsylvania?",    choices: ["Pittsburgh", "Philadelphia", "Harrisburg", "Erie"],    correctAnswer: "Harrisburg"    },     {    ques: "What is the capital of Florida?",    choices: ["Tallahassee", "Tampa", "Miami", "Jacksonville"],    correctAnswer: "Tallahassee"    },    {    ques: "What is the capital of Georgia?",    choices: ["Augusta", "Atlanta", "Savannah"],    correctAnswer: "Atlanta"    } ]; //end of myQuiz array of objects  var questionIndex = -1; // Not started
function nextQuestion() {document.body.innerHTML = ''; ++questionIndex; document.write(myQuiz[questionIndex].ques + "<br />");
for (var j=0; j < myQuiz[questionIndex].choices.length; j++) { document.write("<input type=radio id=myRadio name=radAnswer>" + myQuiz[questionIndex].choices[j] + "<br />"); } if (questionIndex < (myQuiz.length - 1)) { var nextButton = document.createElement("input"); nextButton.type = "button"; nextButton.value = "Next question"; nextButton.addEventListener('click', nextQuestion); document.body.appendChild(nextButton); }};
nextQuestion();

javascript quiz: make all questions, which originally appeared one at a time, appear at end of quiz

All you need to do is add the following at the end of your validate function (but before the return – which you can actually remove):

const divs = document.getElementsByTagName('div') 

for (const div of divs) {
div.style.display = 'block'
div.style.visibility = 'visible'
}

and if you want to have it even more concise you can destructure the style attribute:

const divs = document.getElementsByTagName('div') 

for (const {style} of divs) {
style.display = 'block'
style.visibility = 'visible'
}

how to make quiz questions appear one at a time in javascript

Welcome to Stackoverflow! SO will help you when you hit a dead end, but you have to exhaust all possibilities and be genuinely stuck. There are a ton of resources online about javascript & jQuery, google is your friend :)

To answer the question of "how to make quiz questions appear one at a time in javascript", there are a hundred ways to merengue a purple flamingo. One solution would be to get the total amount of questions and keep track of the current question being displayed. Then when a user clicks next, hide the current question and display the next.http://jsfiddle.net/3kpFV/

//Store the total number of questions
var totalQuestions = $('.questions').size();

//Set the current question to display to 1
var currentQuestion = 0;

//Store the selector in a variable.
//It is good practice to prefix jQuery selector variables with a $
$questions = $('.questions');

//Hide all the questions
$questions.hide();

//Show the first question
$($questions.get(currentQuestion)).fadeIn();

//attach a click listener to the HTML element with the id of 'next'
$('#next').click(function () {

//fade out the current question,
//putting a function inside of fadeOut calls that function
//immediately after fadeOut is completed,
//this is for a smoother transition animation
$($questions.get(currentQuestion)).fadeOut(function () {

//increment the current question by one
currentQuestion = currentQuestion + 1;

//if there are no more questions do stuff
if (currentQuestion == totalQuestions) {

var result = sum_values()

//do stuff with the result
alert(result);

} else {

//otherwise show the next question
$($questions.get(currentQuestion)).fadeIn();

}
});

});

How to display 5 questions from a JavaScript array at the same time in HTML?

EDIT: Here is a repl which shows what you wanted with Next and Previous buttons

Too much was built so rigid around that entire construct.. so editing your code was hard.. instead I just made a dynamic question display setup(n controls the amount of questions displayed because displayQuestion displays all questions that is given with the arr argument)

Now for the step by step walkthrough

There are 3 main functions:

  1. The event listener of startBtn: the first line inside this code simply changes the text displayed from the startButton, not all that important.. right below that is an important variable n which is used in a filter later down in such a way that n CONTROLS the amount of questions that will be displayed at one time
  2. The displayQuestions function: this function takes in 2 arguments; arr and questionBar. arr is the array of questions given(remember it's the event listener that gives an intelligently filtered array of questions). it iterates through each question item, makes an element(which would encompass the question and its options), a function(which would be click listeners for all the different options of the question; and stop listening from all options when one is selected) and then it iterates through the options to append the options to the parent question and add the specialised listener function to each option
  3. The displayResults function: this takes in the results object(in its first argument) and prints the main results to given element(in its second argument)

var questionBar=document.getElementById('questions')

var startBtn=document.getElementById('start')
startBtn.addEventListener('click', async function(){
questionBar.innerHTML="" //important to prevent overlap(move this line to the beginning of the displayQuestions to ONLY show 5 questions at a time on the whole document)
startBtn.innerText="Restart Questions"
var n=5 //change this number to change the amount of questions shown
var results={correct:0,totalPossible:0}
for(var i=0;i<questions.length;i+=n){
var result=await displayQuestions(
questions.filter((a,j)=>j>=i&&j<i+n),
questionBar
)
Object.keys(result).forEach(a=>{
if(a=="correct"){results.correct+=result.correct}
else if(a=="totalPossible"){results.totalPossible+=result.totalPossible}
else{results[a]=result[a]}
})
}
displayResults(results,questionBar)
})

async function displayQuestions(arr,questionBar){
var finished=arr.length //a test for if all questions answered
var answered=0; var correct=0
var corrections={}
arr.forEach(a=>{
var question=document.createElement('div')
question.className="question" //for css to change looks

var options=[] //will become an array of elements(that have the question options) in order to remove event listener from them
//the function below handles when a question option is selected and removes listening when an answer is selected(one can only answer once)
function listen(ev){
var answer=ev.path[0].innerText
if(answer==a.answer){
question.className="correct";correct++;answered++
ev.path[0].className="selected"
corrections[a.numb]={
correct:true, userAnswer:answer, correctAnswer:a.answer
}
}
else{
question.className="wrong";answered++
ev.path[0].className="selected"
corrections[a.numb]={
correct:false, userAnswer:answer, correctAnswer:a.answer
}
}
options.forEach(c=>{c.removeEventListener('click',listen)})
}

var title=document.createElement('span')
title.classList.add('title') //for css to change looks
title.innerText=`(${a.numb}) ${a.question}`
question.appendChild(title)

a.options.forEach(b=>{
var option=document.createElement('div')
option.className="option" //for css to change looks
option.innerText=b
option.addEventListener('click',listen)
options.push(option)
question.appendChild(option)
})
questionBar.appendChild(question)
})
var p=new Promise(results=>{
var i=setInterval(()=>{
if(answered==finished){
clearInterval(i) //the timeout INSIDE the interval ensures that I can fix the time that you have to look at the final display of what was right and wrong before the results function is run
//it's just a personal preference because it looks glitchy when the question immediately goes into results
setTimeout(()=>{
corrections.correct=correct
corrections.totalPossible=finished
results(corrections)
},1000)
}
},0)
})
return await p
}

function displayResults(corrections,elem){
//the corrections object has A LOT of data you can use in MANY ways
console.log(corrections)
var correct=corrections.correct
var totalPossible=corrections.totalPossible
elem.innerText=`You got ${correct} of ${totalPossible}`
}
.wrong {
background-color: red;
border-radius: 5px;
margin: 20px;
}
.correct {
background-color: lightgreen;
border-radius: 5px;
margin: 20px;
}
.question{
background-color: lightblue;
border-radius: 5px;
margin: 20px;
}
.title{
font-weight: bold;
font-family: Verdana;
}
.option{
font-family: Courier, sans-serif;
margin: 5px;
}
.selected{
font-family: Courier, sans-serif;
margin: 5px;
background-color: orange;
}
<div class="start_btn">
<button id="start">Start Questions</button>
</div>
<div id="questions"></div>

<script>
//btw all numb values should be unique.. I'm counting on that xD
let questions = [{
numb: 1,
question: "What does HTML stand for?",
answer: "Hyper Text Markup Language",
options: [
"Hyper Text Preprocessor",
"Hyper Text Markup Language",
"Hyper Text Multiple Language",
"Hyper Tool Multi Language"
]
},
{
numb: 2,
question: "What does CSS stand for?",
answer: "Cascading Style Sheet",
options: [
"Common Style Sheet",
"Colorful Style Sheet",
"Computer Style Sheet",
"Cascading Style Sheet"
]
},
{
numb: 3,
question: "What does PHP stand for?",
answer: "Hypertext Preprocessor",
options: [
"Hypertext Preprocessor",
"Hypertext Programming",
"Hypertext Preprogramming",
"Hometext Preprocessor"
]
},
{
numb: 4,
question: "What does SQL stand for?",
answer: "Structured Query Language",
options: [
"Stylish Question Language",
"Stylesheet Query Language",
"Statement Question Language",
"Structured Query Language"
]
},
{
numb: 5,
question: "What does XML stand for?",
answer: "eXtensible Markup Language",
options: [
"eXtensible Markup Language",
"eXecutable Multiple Language",
"eXTra Multi-Program Language",
"eXamine Multiple Language"
]
},
{
numb: 6,
question: "Why did the cow cross the road",
answer: "There was no road, it was grass",
options: [
"idk LOL",
"COWS CAN'T SWIM",
"There was no road, it was grass",
"Bruh pls, NEXT"
]
},
{
numb: 7,
question: "How to select element with 2 classes(CSS)",
answer: "Chain dots like: .a.b",
options: [
"Chain dots like: .a.b",
"It's impossible",
"Sequence dots like: .a .b",
"explore the universe, then come back"
]
},
{
numb: 8,
question: "What is 9+10?",
answer: "Nineteen",
options: [
"Twenty one",
"nothing at all, irrelevant",
"IDK, YOU TELL ME",
"Nineteen"
]
},
{
numb: 9,
question: "How does a C linked list work?",
answer: "structs and pointer logic",
options: [
"high level javascript magic",
"some random module",
"that doesn't exist",
"structs and pointer logic"
]
},
{
numb: 10,
question: "Is light a particle?",
answer: "It behaves like a particle AND a wave",
options: [
"Affirmitave",
"Nope, not even close",
"It behaves like a particle AND a wave",
"It's a unicorn"
]
},
{
numb: 11,
question: "What is a bit?",
answer: "A binary digit",
options: [
"A binary digit",
"BEEP BOOP",
"69",
"idk smh xD"
]
}
]
</script>

Html Quiz not working js questions not showing up

You mixed up if with for here:

if (i = 0; i < choicesList; i++) {
choice = questions[curruntQ].choices[i];
$('<li><input type="radio" value=' + i + ' name="dynradio"/>' + choice + '<li>').appendTo(choicesList);
}

However, the for loop won't run, since choicesList isn't a number but an element. You mistaked it for numChoices.

You also made a typo. $(document).find(".quizContainer > .choicesList"); should be $(document).find(".quizContainer > .choiceList"); (no s).

Try this:

var questions = [{
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}, {
question: "What is the baby of a Moth",
choices: ["baby", "infant", "kitt", "larva"],
correctAns: 4
}];
var curruntQ = 0;
var correctA = 0;
var quizO = false;

$(document).ready(function() {
displayCurrentQuestion();
$(this).find('.quizMessage').hide();
$(this).find('.nextButton').on("click", function() {
if (!quizO) {
value = $("input[type='radio']:checked").val();
if (value == undefined) {
$(document).find(".quizMessage").text("Please select an answer");
$(document).find(".quizMessage").show();
} else {
$(document).find(".quizMessage").hide();
if (value == question[curruntQ].correctA) {
correctA++;
}
curruntQ++;
if (curruntQ < question.length) {
displayCurrentQuestion();
} else {
displatScore();
$(document).find(".nextButton").text("Take again!");
quizO = true;
}
}
} else {
quizO = false;
$(document).find(".nextButton").text("Next question");
resetQuiz();
displayCurrentQuestion();
hideScore();
}
});
});

function displayCurrentQuestion() {
console.log("On display current question")
var question = questions[curruntQ].question;
var questionClass = $(document).find(".quizContainer > .question");
var choicesList = $(".choiceList");
var numChoices = questions[curruntQ].choices.length;
$(questionClass).text(question);
$(choicesList).find("li").remove();
var choice;
for (i = 0; i < numChoices; i++) {
choice = questions[curruntQ].choices[i];
$('<li><input type="radio" value=' + i + ' name="dynradio"/>' + choice + '<li>').appendTo(choicesList);

}
}

function resetQuiz() {
currentQ = 0;
correctA = 0;
hideScore();
}

function displatScore() {
$(document).find(".quizContainer > .result").text("You scored" + correctA + " out of: " + questions.length);
$(document).find(".quizContainer > .result").show();
}

function hideScore() {
$(document).find(".result").hide();
}
@import url(https://fonts.googleapis.com/css2?family=Caveat);
h1 {
font-family: 'Caveat', serif;
text-align: center;
color: #000;
font-size: 35px;
font-weight: lighter;
}

ul {
list-style: none;
}

li {
font-family: 'Pacifico', serif;
font-size: 2em;
color: #feb135;
}

input[type=radio] {
border: 0px;
width: 20px;
height: 2em;
}

p {
font-family: 'Caveat';
}

.quizContainer {
background-color: #000398;
border-radius: 8px;
width: 75%;
margin: auto;
margin-top: 190px;
padding-top: 5px;
position: relative;
}

.nextButton {
border-radius: 6px;
width: 150px;
height: 40px;
text-align: center;
background-color: #cc0000;
color: #fff;
font-family: 'Caveat', serif;
font-weight: bold;
position: relative;
margin: auto;
padding-top: 20px;
}

.question {
font-family: 'Caveat';
font-size: 2em;
width: 90%;
height: auto;
margin: auto;
border-radius: 6px;
background-color: #f2f205;
text-align: center;
color: #27a63;
}

.quizMessage {
background-color: peachpuff;
border-radius: 6px;
width: 30%;
margin: auto;
text-align: center;
padding: 2px;
font-family: "Caveat";
color: red;
}

.choiceList {
font-family: 'Caveat';
}

.result {
width: 30%;
height: auto;
border-radius: 6px;
background-color: linen;
margin: auto;
margin-bottom: 35px;
text-align: center;
font-family: 'Caveat';
}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Baby animal names</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
<div class="quizContainer">
<h1>Chooze the correct animal baby names!</h1>
<div class="question"></div>
<ul class="choiceList"></ul>
<div class="quizMessage"></div>
<div class="result"></div>
<div class="nextButton">Next Question</div><br/>
</div>

<script type="text/javascript" src="script.js"></script>

</body>

</html>

How to display only one data at a time in an online quiz

I kinda get what your asking, Ive jotted out the basic structure. This can all be done on one page, hope it helps.

EDIT:

As im such a nice guy heres a complete script, using my prev suggestion ;p

<?php
session_start();
echo '<h2>ONLINE QUIZ</h2>';


//Scores
if($_SERVER['REQUEST_METHOD']=='GET' && isset($_GET['scores'])){
echo 'Basic output for scores';
echo '<pre>';
print_r($_SESSION['answers']);
echo '</pre>';
unset($_SESSION['answers']);
unset($_SESSION['question']);
}


//Session question/array is set
if(isset($_SESSION['question']) && isset($_SESSION['questions_array'])){

//Handle prev question post
if($_SERVER['REQUEST_METHOD']=='POST'){
//process prev question
$_SESSION['answers'][$_SESSION['question']-1]=(0+$_POST['answer']);
}

if($_SESSION['question'] < $_SESSION['total_question']){
$q=$_SESSION['question'];
//EDIT - Shuffle answers for output
//Hold the question into a var
$question = $_SESSION['questions_array'][$q][0];
//unset the question from the array
unset($_SESSION['questions_array'][$q][0]);
//put all the pos answers into a new array
$answers = $_SESSION['questions_array'][$q];
//shuffle the answers
shuffle($answers);


echo '<form method="POST" action="">
<h3>'.$question.'</h3>';
//loop through the answers
foreach($answers as $key=>$value){


Related Topics



Leave a reply



Submit