How to create a quiz-like functionality using Syncfusion Radio Buttons and Progress Bars
This article provides a step-by-step guide on how to create a quiz-like functionality using radio buttons for options and progress bars to display the user’s progress and score. The example demonstrates how to process quiz data, create radio buttons dynamically, and handle user interactions to update the progress bars accordingly.
Prerequisites
Before implementing the quiz functionality, ensure you have the following:
- A basic understanding of HTML, CSS, and TypeScript.
- The Syncfusion TypeScript library included in your project for the progress bar component.
Step 1: Define Quiz Data
First, define an array of objects representing the quiz data. Each object should contain a question, multiple-choice answers, and the correct answer key.
let qdata: any = [
// ... (list of question objects)
{ question: "Who owns the pet?", A: "kelvin", B: "Agnes", C: "mike", D: "Costa", answer: "A" },
{ question: "Who owns the bike?", A: "kelvin", B: "Agnes", C: "mike", D: "Costa", answer: "B" },
{ question: "Who owns the car?", A: "kelvin", B: "Agnes", C: "mike", D: "Costa", answer: "B" },
{ question: "Who owns the house?", A: "kelvin", B: "Agnes", C: "mike", D: "Costa", answer: "A" },
{ question: "What is the capital of France?", A: "London", B: "Berlin", C: "Rome", D: "Paris", answer: "D" },
{ question: "Which planet is known as the Red Planet?", A: "Mars", B: "Venus", C: "Jupiter", D: "Saturn", answer: "A" },
{ question: "Who wrote the play 'Romeo and Juliet'?", A: "William Shakespeare", B: "Charles Dickens", C: "Mark Twain", D: "Jane Austen", answer: "A" },
{ question: "What is the chemical symbol for gold?", A: "Au", B: "Ag", C: "Go", D: "Gl", answer: "A" },
{ question: "Which gas do plants use for photosynthesis?", A: "Oxygen", B: "Carbon Dioxide", C: "Nitrogen", D: "Hydrogen", answer: "B" },
{ question: "Who is the author of 'To Kill a Mockingbird'?", A: "Harper Lee", B: "J.K. Rowling", C: "George Orwell", D: "Mark Twain", answer: "A" }
];
Step 2: Initialize Progress Bars
Create two progress bars using Syncfusion’s ProgressBar component: one for tracking the total number of questions answered and another for tracking the number of correct answers.
let progressBarCorrect = new ProgressBar({
type: 'Linear',
value: 0,
maximum: 10
});
progressBarCorrect.appendTo('#progress-bar-correct');
let progressBarAll = new ProgressBar({
type: 'Linear',
value: 0,
maximum: 10
});
progressBarAll.appendTo('#progress-bar-all');
Step 3: Process Quiz Data
Write a function to process the quiz data and structure it for easy manipulation when creating radio buttons.
function processQuestion(qdata: any) {
// ... (logic to process questions)
let qbObject: any = [];
for (let i: number = 0; i < qdata.length; i++) {
let obj: any = {};
obj.question = qdata[i].question;
obj.answerKey = qdata[i].answer;
obj.answer = qdata[i][qdata[i].answer];
obj.choices = [];
obj.choices.push({ id: 'qtn' + i + '_' + 1, name: 'qtn' + i, label: qdata[i].A });
obj.choices.push({ id: 'qtn' + i + '_' + 2, name: 'qtn' + i, label: qdata[i].B });
obj.choices.push({ id: 'qtn' + i + '_' + 3, name: 'qtn' + i, label: qdata[i].C });
obj.choices.push({ id: 'qtn' + i + '_' + 4, name: 'qtn' + i, label: qdata[i].D });
qbObject.push(obj);
}
return qbObject;
}
Step 4: Create Radio Buttons
Implement a function to dynamically create radio buttons for each question and its corresponding choices.
function createRadioBtns(qObject: any) {
const tableElem: HTMLElement = (document.getElementById('control-section') as HTMLElement).querySelector('table');
for (let i: number = 0; i < qObject.length; i++) {
let trElem: HTMLElement = document.createElement("tr");
let tdElem: HTMLElement = document.createElement("td");
const questionElem: HTMLSpanElement = document.createElement("span");
questionElem.textContent = qObject[i].question;
tdElem.appendChild(questionElem); trElem.appendChild(tdElem);
tdElem = document.createElement("td"); trElem.appendChild(tdElem); tableElem.appendChild(trElem);
trElem = tableElem.lastElementChild as HTMLElement;
tdElem = trElem.lastElementChild as HTMLElement;
qObject[i].choices.forEach((choice) => {
const input: any = document.createElement("input");
input.type = "radio";
input.id = choice.id;
tdElem.appendChild(input);
const radioButton: RadioButton = new RadioButton({ label: choice.label, name: choice.name, value: choice.label, change: changeHandler });
radioButton.appendTo("#" + input.id);
});
tdElem = document.createElement("td");
const answerElem: HTMLElement = document.createElement("span");
answerElem.className = 'e-answer';
answerElem.id = 'ans_' + i;
tdElem.appendChild(answerElem); trElem.appendChild(tdElem);
}
}
Step 6: Track Progress and Score
Use variables to keep track of the number of questions answered and the number of correct answers. Update these variables within the change handler function.
let answeredQuestions: number = 0;
let correctAnswers: number = 0;
let questionStats: object = [];
Step 5: Handle User Interactions
Define a change handler function to update the progress bars and display whether the user’s answer is correct or incorrect.
function changeHandler(args: { event: Event; value: string }) {
const idx = parseInt((args.event.target as HTMLInputElement).name.split('qtn')[1]);
if (!questionStats[idx]) {
questionStats[idx] = { answered: false, correct: false };
}
if (!questionStats[idx].answered) {
questionStats[idx].answered = true;
answeredQuestions++;
if (answeredQuestions > 10) {
answeredQuestions = 10;
}
(document.getElementById('progress-text') as HTMLElement).textContent = (answeredQuestions * 10) + '%';
}
if (args.value !== qObject[idx].answer) {
(document.getElementById('ans_' + idx) as HTMLElement).textContent = 'Answer is: ' + qObject[idx].answerKey;
if (questionStats[idx].correct) {
questionStats[idx].correct = false;
if (correctAnswers > 0) {
correctAnswers--;
}
const overallCorrectPercentage = correctAnswers * 10;
(document.getElementById('correct-text') as HTMLElement).textContent = overallCorrectPercentage + '%';
}
} else {
if (!questionStats[idx].correct) {
questionStats[idx].correct = true;
correctAnswers++;
const overallCorrectPercentage: number = correctAnswers * 10;
(document.getElementById('correct-text') as HTMLElement).textContent = overallCorrectPercentage + '%';
}
(document.getElementById('ans_' + idx) as HTMLElement).textContent = 'Answer is Right';
}
}
Demo and Sample Code
For a live demonstration and to experiment with the code, you can visit the following demo sample link:
Demo Sample Link: Quiz Demo
Conclusion
By following these steps, you can create an interactive quiz with radio buttons and progress bars using JavaScript and Syncfusion components. This functionality can be customized and extended to fit various quiz formats and styles.
Additional References
- Syncfusion ProgressBar Documentation: Syncfusion ProgressBar
- JavaScript Event Handling: MDN Web Docs - Event reference
- Creating and Modifying HTML Elements: MDN Web Docs - Document.createElement()