I am developing a simple quiz app with vanilla JavaScript and HTML. The functionality to know if the chosen answer is correct or incorrect and display some feedback is working, but not the functionality to set the .quiz__marker div's data-attribute to "Correct" or "Incorrect" when the question's radio button is selected. My simplified code is included in the snippet below.
I have set the .quiz__marker divs to either be green or red depending on if the correct or incorrect answer is selected. As you can see, all of the circles are set to green or red when the radio button is selected.
How should I adjust my JS code to only apply the color change to a single circle? Also, what would I need to implement to have the color maintained throughout the quiz duration?
I am learning JavaScript as I go. Vanilla JS answers are preferred.
Cheers!
Update - Included full quiz.js for review purposes
function answerTracker() {
const tracker = document.querySelector(".quiz__tracker");
// Each quiz contains eight or less questions
const questions = 8;
for (let i = 1; i <= questions; i++) {
let trackerMarker = document.createElement("div");
trackerMarker.className = "quiz__marker";
trackerMarker.id = "marker_" + i;
trackerMarker.setAttribute("data-answer", "");
tracker.appendChild(trackerMarker);
}
}
function questionMarkers() {
let labels = document.querySelectorAll("div[class*='rsform-block-question'] .formControlLabel");
let count = labels.length;
for (let i = 0; i < count; i++) {
let marker = `<span class="question-marker">${i + 1}</span>`;
labels[i].insertAdjacentHTML("beforebegin", marker);
}
}
const runQuiz = (() => {
// Generate tracker
answerTracker();
// Append question markers to labels
questionMarkers();
// Set quiz score to zero
let score = 0;
let markers = document.querySelectorAll(".quiz__marker");
let answers = document.querySelectorAll(".rsform-radio");
answers.forEach(function (answer) {
answer.addEventListener("click", (e) => {
let target = e.target;
let container = target.closest(".formContainer");
let correct = container.querySelector("div[class$='true']");
let wrong = container.querySelector("div[class$='false']");
let feedback = container.querySelector("div[class$='feedback']");
let question = container.querySelector("div[class*='rsform-block-question']");
let next = container.querySelector(".js-btn--next.success");
let submit = container.querySelector(".js-btn--submit.rsform-submit-button");
if (e.target.value == "t") {
// If answer is correct, increment the user's score by one
score++;
correct.style.display = "block";
wrong.style.display = "none";
feedback.style.display = "block";
document.getElementById("marker_" + e.target.dataset.num).setAttribute("data-answer", "Correct");
} else {
correct.style.display = "none";
wrong.style.display = "block";
feedback.style.display = "block";
document.getElementById("marker_" + e.target.dataset.num).setAttribute("data-answer", "Incorrect");
}
if (next !== null && next !== "") {
next.style.display = "block";
}
if (submit !== null && submit !== "") {
submit.style.display = "block";
}
question.style.display = "none";
});
});
// If this is the final question in the quiz, assign the score variable to the final-score hidden HTML field
// document.getElementById("final-score").value = score;
})();
function answerTracker() {
const tracker = document.querySelector(".quiz__sidebar");
// Each quiz contains eight questions
const questions = 8;
for (let i = 1; i <= questions; i++) {
let trackerMarker = document.createElement("div");
trackerMarker.className = "quiz__marker";
trackerMarker.setAttribute("data-answer", "");
tracker.appendChild(trackerMarker);
}
}
const runQuiz = (() => {
// Generate answer tracker
answerTracker();
// Set quiz score to zero
let score = 0;
// Get node list of .quiz__marker DIVs
let markers = document.querySelectorAll(".quiz__marker");
// Get node list of answer radio buttons
let answers = document.querySelectorAll(".rsform-radio");
answers.forEach(function(answer) {
answer.addEventListener("click", (e) => {
let target = e.target;
let container = target.closest(".formContainer");
let correct = container.querySelector("div[class$='true']");
let wrong = container.querySelector("div[class$='false']");
let feedback = container.querySelector("div[class$='feedback']");
let question = container.querySelector("div[class*='rsform-block-question']");
let next = container.querySelector(".js-btn--next.success");
if (e.target.value == "t") {
// If answer is correct, increment the user's score by one
score++;
correct.style.display = "block";
wrong.style.display = "none";
feedback.style.display = "block";
} else {
correct.style.display = "none";
wrong.style.display = "block";
feedback.style.display = "block";
}
// Loop through node list and set data-attribute to "Correct" or "Incorrect" depending on e.target value
Array.from(markers).forEach(link => {
if (e.target.value == "t") {
link.setAttribute("data-answer", "Correct");
} else {
link.setAttribute("data-answer", "Incorrect");
}
});
// If question has been answered, display the next button
if (next !== null && next !== "") {
next.style.display = "block";
}
});
});
// If this is the final question in the quiz, assign the score variable to the final-score hidden HTML field
// document.getElementById("final-score").value = score;
})();
.quiz__sidebar .quiz__marker {
display: inline-block;
width: 20px;
height: 20px;
margin: 6px;
background-color: grey;
border-radius: 50%;
}
.quiz__sidebar .quiz__marker[data-answer="Correct"] {
background-color: green;
}
.quiz__sidebar .quiz__marker[data-answer="Incorrect"] {
background-color: red;
}
form.quiz__form .formHidden,
form.quiz__form div[class$="true"],
form.quiz__form div[class$="false"],
form.quiz__form div[class$="feedback"],
form.quiz__form .rsform-block .rsform-button {
display: none;
}
<div class="quiz">
<div class="quiz__sidebar"></div>
<form class="quiz__form">
<div class="formContainer">
<div class="rsform-block-question-one">
<input type="radio" name="form[question-one]" value="f" id="question-one0" class="rsform-radio">
<label for="question-one0">To attract a mate</label>
<br>
<input type="radio" name="form[question-one]" value="t" id="question-one1" class="rsform-radio">
<label for="question-one1">To defend themselves against predators</label>
<br>
<input type="radio" name="form[question-one]" value="f" id="question-one2" class="rsform-radio">
<label for="question-one2">To mark their territory</label>
<br>
<input type="radio" name="form[question-one]" value="f" id="question-one3" class="rsform-radio">
<label for="question-one3">Because they like the smell</label>
</div>
<div class="rsform-block-question-one-true">
<p>
<strong>Correct!</strong>
</p>
</div>
<div class="rsform-block-question-one-false">
<p>
<strong>Nice try</strong>
</p>
</div>
<div class="rsform-block-question-one-feedback">
<p>Skunks spray an extremely offensive odour to make predators go away and leave them alone. If they feel their life is in danger, they have no other defence as they cannot run fast, climb, burrow under the ground, or fight.</p>
</div>
<div class="rsform-block">
<button type="button" class="btn--next js-btn--next rsform-button success button" style="display: none;">
Next
</button>
</div>
</div>
<div class="formContainer formHidden">
<div class="rsform-block-question-two">
<input type="radio" name="form[question-two]" value="f" id="question-two0" class="rsform-radio">
<label for="question-two0">1 cup</label>
<br>
<input type="radio" name="form[question-two]" value="f" id="question-two1" class="rsform-radio">
<label for="question-two1">Endless supply</label>
<br>
<input type="radio" name="form[question-two]" value="t" id="question-two2" class="rsform-radio">
<label for="question-two2">2 tbsp</label>
<br>
<input type="radio" name="form[question-two]" value="f" id="question-two3" class="rsform-radio">
<label for="question-two3">1 tsp</label>
</div>
<div class="rsform-block-question-two-true">
<p>
<strong>Correct!</strong>
</p>
</div>
<div class="rsform-block-question-two-false">
<p>
<strong>Nice try</strong>
</p>
</div>
<div class="rsform-block-question-two-feedback">
<p>Skunks have only 2 tbsp (30ml) of spray and it takes them more than a week to re-supply. They cannot spray every day as they will simply run out. Skunks use spraying as a last resort only as if they run out, they are defenceless against predators.</p>
</div>
<div class="rsform-block">
<button type="button" class="btn--next js-btn--next rsform-button success button" style="display: none;">
Next
</button>
</div>
</div>
</form>
</div>
You need to add some characteristic "markers" for the quiz markers, for example an id with the question number:
for (let i = 1; i <= questions; i++) {
let trackerMarker = document.createElement("div");
trackerMarker.className = "quiz__marker";
trackerMarker.id = "marker_" + i; // specific id for each marker
trackerMarker.setAttribute("data-answer", "");
tracker.appendChild(trackerMarker);
}
and then don't loop through every marker - set the color for the marker with the same number as the question. Something like:
document.getElementById("marker_" + questionNumber).setAttribute("data-answer", "Correct");
I can't see the code to handle click on the next button, but it doesn't matter for the question.
function answerTracker() {
const tracker = document.querySelector(".quiz__sidebar");
// Each quiz contains eight questions
const questions = 8;
for (let i = 1; i <= questions; i++) {
let trackerMarker = document.createElement("div");
trackerMarker.className = "quiz__marker";
trackerMarker.id = "marker_" + i;
trackerMarker.setAttribute("data-answer", "");
tracker.appendChild(trackerMarker);
}
}
const runQuiz = (() => {
// Generate answer tracker
answerTracker();
// Set quiz score to zero
let score = 0;
// Get node list of .quiz__marker DIVs
let markers = document.querySelectorAll(".quiz__marker");
// Get node list of answer radio buttons
let answers = document.querySelectorAll(".rsform-radio");
answers.forEach(function(answer) {
answer.addEventListener("click", (e) => {
let target = e.target;
let container = target.closest(".formContainer");
let correct = container.querySelector("div[class$='true']");
let wrong = container.querySelector("div[class$='false']");
let feedback = container.querySelector("div[class$='feedback']");
let question = container.querySelector("div[class*='rsform-block-question']");
let next = container.querySelector(".js-btn--next.success");
if (e.target.value == "t") {
// If answer is correct, increment the user's score by one
score++;
correct.style.display = "block";
wrong.style.display = "none";
feedback.style.display = "block";
document.getElementById("marker_" + e.target.dataset.num).setAttribute("data-answer", "Correct");
} else {
correct.style.display = "none";
wrong.style.display = "block";
feedback.style.display = "block";
document.getElementById("marker_" + e.target.dataset.num).setAttribute("data-answer", "Incorrect");
}
// If question has been answered, display the next button
if (next !== null && next !== "") {
next.style.display = "block";
}
});
});
// If this is the final question in the quiz, assign the score variable to the final-score hidden HTML field
// document.getElementById("final-score").value = score;
})();
.quiz__sidebar .quiz__marker {
display: inline-block;
width: 20px;
height: 20px;
margin: 6px;
background-color: grey;
border-radius: 50%;
}
.quiz__sidebar .quiz__marker[data-answer="Correct"] {
background-color: green;
}
.quiz__sidebar .quiz__marker[data-answer="Incorrect"] {
background-color: red;
}
form.quiz__form .formHidden,
form.quiz__form div[class$="true"],
form.quiz__form div[class$="false"],
form.quiz__form div[class$="feedback"],
form.quiz__form .rsform-block .rsform-button {
display: none;
}
<div class="quiz">
<div class="quiz__sidebar"></div>
<form class="quiz__form">
<div class="formContainer">
<div class="rsform-block-question-one">
<input type="radio" name="form[question-one]" data-num="1" value="f" id="question-one0" class="rsform-radio">
<label for="question-one0">To attract a mate</label>
<br>
<input type="radio" name="form[question-one]" data-num="1" value="t" id="question-one1" class="rsform-radio">
<label for="question-one1">To defend themselves against predators</label>
<br>
<input type="radio" name="form[question-one]" data-num="1" value="f" id="question-one2" class="rsform-radio">
<label for="question-one2">To mark their territory</label>
<br>
<input type="radio" name="form[question-one]" data-num="1" value="f" id="question-one3" class="rsform-radio">
<label for="question-one3">Because they like the smell</label>
</div>
<div class="rsform-block-question-one-true">
<p>
<strong>Correct!</strong>
</p>
</div>
<div class="rsform-block-question-one-false">
<p>
<strong>Nice try</strong>
</p>
</div>
<div class="rsform-block-question-one-feedback">
<p>Skunks spray an extremely offensive odour to make predators go away and leave them alone. If they feel their life is in danger, they have no other defence as they cannot run fast, climb, burrow under the ground, or fight.</p>
</div>
<div class="rsform-block">
<button type="button" class="btn--next js-btn--next rsform-button success button" style="display: none;">
Next
</button>
</div>
</div>
<div class="formContainer formHidden">
<div class="rsform-block-question-two">
<input type="radio" name="form[question-two]" data-num="2" value="f" id="question-two0" class="rsform-radio">
<label for="question-two0">1 cup</label>
<br>
<input type="radio" name="form[question-two]" data-num="2" value="f" id="question-two1" class="rsform-radio">
<label for="question-two1">Endless supply</label>
<br>
<input type="radio" name="form[question-two]" data-num="2" value="t" id="question-two2" class="rsform-radio">
<label for="question-two2">2 tbsp</label>
<br>
<input type="radio" name="form[question-two]" data-num="2" value="f" id="question-two3" class="rsform-radio">
<label for="question-two3">1 tsp</label>
</div>
<div class="rsform-block-question-two-true">
<p>
<strong>Correct!</strong>
</p>
</div>
<div class="rsform-block-question-two-false">
<p>
<strong>Nice try</strong>
</p>
</div>
<div class="rsform-block-question-two-feedback">
<p>Skunks have only 2 tbsp (30ml) of spray and it takes them more than a week to re-supply. They cannot spray every day as they will simply run out. Skunks use spraying as a last resort only as if they run out, they are defenceless against predators.</p>
</div>
<div class="rsform-block">
<button type="button" class="btn--next js-btn--next rsform-button success button" style="display: none;">
Next
</button>
</div>
</div>
</form>
</div>
Related
I'm creating a quiz that contains 10 questions: 5 multiple choice through radio input and 5 written answers through text input. See code for both inputs below. But I would also like to add a score system to these questions. I found a nice script here on stack overflow that can keep the score while user enters form input. I will add it below.
The script I use to check answers from radio input:
$(document).ready(function(){
$('input[name=radio1]').change(function(){
$('.alert').remove();
if($('input[name=radio1]:checked').val() === "1") {
$(this).parent().append('<span class="correct">✓ Correct!</span>');
} else {
$(this).parent().append('<span class="incorrect">✗ Correct answer = B</span>');
}
});
});
The correct anser given is based on value="1". The other answers have value="0".
The script I use to check answers from text input:
$('submit').on('click', function() {
markAnswers(1)
});
var answers = {
q1: ["Auto's"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
let userAnswer = this.value.replace(/[^\w\'\,\-\?\!\"\:\—\;]/g,'');
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
The correct value from text input is determined by this script above.
Now, the script I found that keeps the score, collects score through data-score=. But I was thinking to just use value instead. See original script below:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
The script can be found here: https://stackoverflow.com/a/58297288/4546157
It is really nice. It keeps the score but it also shows you if you have completed the form or not.
I would like each correct answer to have a value of 1 so at the end of the quiz the user can have a maximum score of 10/10. But, a big but, I don't know how to implement it. Hoping to see suggestions or solutions from you guys. Thank you!
You would do it something like this. Though it's bad practice to use globally available variables, but for the sake of simplicity i put them there. Better to wrap everything in a div and store score/progress as data attributes.
Pen: https://codepen.io/lenadax/pen/QWQqMxP?editors=1111
// global vars, put them somewhere else
var progress = 0;
var score = 0;
$('form.question').each(function(i, el) {
// I'm lazy so form id is the same as input name for each question
let inputs = $(`input[name=${$(this).attr('id')}]`);
inputs.on('change', function() {
// increase progress by 1 if button has been selected.
progress++;
if ($(this).val() === "1") {
// increase score if correct choice selected
score++;
$('<span class="result correct">').text('✓ Correct!').appendTo(el);
} else {
$('<span class="result incorrect">').text('X Incorrect!').appendTo(el);
}
// get number of questions
let question_count = $('form.question').length;
// disable after choosing for less hassle
inputs.prop('disabled', true);
// calculate the progress in percent
let progress_num = progress / question_count * 100;
$('.perc').text(progress_num);
$('#score').text(`${score} / ${question_count}`);
});
})
input {
display: inline-block;
}
label {
display: inline-block;
}
button {
display: block;
}
form {
width: 200px;
border: 1px solid gray;
margin: 10px;
padding:10px 5px;
}
.result {
display: block;
}
.result.incorrect {
color: red;
}
.result.correct {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="question" id="question1">
<span>Question 1</span>
</p>
<input name="question1" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question1" id="answer2" type="radio" value="1"/>
<label for="answer2">Right answer</label>
</form>
<form class="question" id="question2">
<span>Question 2</span>
</p>
<input name="question2" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question2" id="answer2" type="radio" value="0"/>
<label for="answer2">Wrong answer</label>
</p>
<input name="question2" id="answer3" type="radio" value="1"/>
<label for="answer3">Right answer</label>
</form>
<h5>Done <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
its a quiz app where clicking on replay button is supposed to restart the quiz and the given event listener code is used when the user selects an answer for question. it works completely fine during first time but when the quiz restarts, the event listener fires twice and if again replay is clicked , then the event listener for selecting correct option fires thrice
let chosen = document.getElementsByClassName("option");
console.log('options',chosen);
for (let choosed of chosen) {
choosed.addEventListener("click", (e) => {
clearInterval(myVar);
clearInterval(counterLine);
console.log("you have choosen");
next.classList.add("next-show");
next.classList.remove("next-hide");
if (questionCount == 10) {
finish.classList.add("next-show");
finish.classList.remove("next-hide");
}
let choosenOption = e.target.className;
choosenOption = choosenOption.substr(7, 14);
let correctOption = arrayOFCorrectAnswers[questionCount - 1];
if (correctOption.includes(choosenOption)) {
colorGreen(e.target);
score++;
} else {
colorRed(e.target);
}
});
}
<div class="question-answer">
<div class="question">
<h2 id="question">Question Incoming.....</h2>
</div>
<div class="options-answers">
<div class="option" id="option1">option1 </div>
<div class="option" id="option2">option2</div>
<div class="option" id="option3">option3</div>
<div class="option" id="option4">option4</div>
</div>
</div>
this is the html
I tried to follow the OP example and couldn't understand it very well. I did notice that it is a quiz without any form controls (not even a <button>). If you are interacting with the user and require input from said user it would behoove you to use <form>, <input>, <button>, etc.
The demo below has:
init() which wraps around all of the variables and functions acting as a closure. It passes 3 arrays.
init() is ran only once. It will register the 'submit' event to the <form> and register the 'click' event to a <button>. It also runs spawnQA() which changes the text of the question and the 4 options.
The options are <input type='radio'> and <label>
const questions = ['Question 1', 'Question 2', 'Question 3', 'Question 4'];
const options = [
['1.1', '1.2', '1.3', '1.4'],
['2.1', '2.2', '2.3', '2.4'],
['3.1', '3.2', '3.3', '3.4'],
['4.1', '4.2', '4.3', '4.4']
];
const answers = [1, 0, 3, 2];
const init = (questions, options, answers) => {
const form = document.forms.QA;
const io = form.elements;
const Q = document.getElementById('question');
const inst = document.querySelector('section');
const list = document.querySelector('ol');
const display = document.querySelector('.display');
let count = parseInt(io.counter.value);
let score = parseInt(io.correct.value);
const endQuiz = () => {
Q.textContent = "Quiz Completed";
inst.classList.toggle('hide');
list.classList.toggle('hide');
io.btn.classList.toggle('hide');
io.rst.classList.toggle('hide');
display.textContent = `Score: ${score}`;
return false;
};
const resetQuiz = event => {
inst.classList.toggle('hide');
list.classList.toggle('hide');
io.btn.classList.toggle('hide');
io.rst.classList.toggle('hide');
count = 0;
score = 0;
spawnQA(questions, options, answers, count);
form.reset();
};
const spawnQA = (questions, options, answers, count) => {
if (count >= answers.length) {
endQuiz();
return false;
}
const opts = [...document.querySelectorAll('.option')];
Q.textContent = `${count+1}. ${questions[count]}`;
opts.forEach((label, index) => {
label.textContent = options[count][index];
});
return false;
};
const nextQuestion = event => {
event.preventDefault();
const opts = [...io.options];
for (let [idx, opt] of opts.entries()) {
if (opt.checked) {
score = answers[count] === idx ? ++score : score;
}
}
count++;
io.counter.value = count;
io.correct.value = score;
spawnQA(questions, options, answers, count);
console.log('score: ' + score);
console.log('count: ' + count);
};
form.onsubmit = nextQuestion;
io.rst.onclick = resetQuiz;
spawnQA(questions, options, answers, count);
};
init(questions, options, answers);
.hide {
display: none
}
ol {
list-style-type: lower-alpha;
}
button {
cursor: pointer;
}
input,
label {
display: inline-block;
vertical-align: text-top;
}
/* SO Console Display - Right Side Column */
.as-console-wrapper {
width: 50% !important;
min-height: 100%;
margin-left: 50%;
font-variant: normal;
}
.as-console-row.as-console-row::after {
content: '';
padding: 0;
margin: 0;
border: 0;
width: 0;
}
<form id="QA">
<input id='correct' type='hidden' value='0'>
<input id='counter' type='hidden' value='0'>
<fieldset>
<legend id="question">Question Incoming.....</legend>
<ol>
<li>
<input id='option1' name='options' type='radio'>
<label for='option1' class='option'>Option 1</label>
</li>
<li>
<input id='option2' name='options' type='radio'>
<label for='option2' class='option'>Option 2</label>
</li>
<li>
<input id='option3' name='options' type='radio'>
<label for='option3' class='option'>Option 3</label>
</li>
<li>
<input id='option4' name='options' type='radio'>
<label for='option4' class='option'>Option 4</label>
</li>
</ol>
<section class='hide'>
<p class='display'></p>
<p>Click "Reset" to reset quiz.</p>
</section>
</fieldset>
<button id='btn'>Next</button>
<button id='rst' class='hide' type='button'>Reset</button>
</form>
Does anyone know what's wrong with start1()? I know that something is not right but I just can't figure what is it.
I have got this school project where i need to do a quiz and record the time that people need to answer all the questions. I've tried everything i know but nothing works. please help
<body>
<div id="classic">
<input type="button" onclick="start1= setInterval(contador, 1000)" value="yes">
<input type="button" onclick="back1()" value="Menu">
</div>
<div id="quizr" hidden>
<h1> who sings the song </h1>
<div id="P1">
<p>1.'Thinking Out Loud'</p>
A)<input type="radio" name="q1" id="q1r1" > Hozier<br>
B)<input type="radio" name="q1" id="q1r2" > Jason Derulo<br>
C)<input type="radio" name="q1" id="q1r3" > Ed Sheeran<br>
D)<input type="radio" name="q1" id="q1r4" > Mr. Probz<br>
<br>
<input type="button" onclick='go1()' value="next »" >
</div>
<div id="P2" hidden>
<p>2.'GANGNAM STYLE'</p>
A)<input type="radio" name="q15" id="q15r1" > Tori Kelly<br>
B)<input type="radio" name="q15" id="q15r2" > Jessie J<br>
C)<input type="radio" name="q15" id="q15r3" > Beyoncé<br>
D)<input type="radio" name="q15" id="q15r4" > Psy<br>
<br>
<input type="button" onclick='verify1= clearInterval(start1)'value="submit">
</div>
</div>
<div id="result" hidden></div>
function start1()
{
document.getElementById("classic").hidden=true;
document.getElementById("quizr").hidden=false;
}
var t= 0;
function contador()
{
document.getElementById("resultado").innerHTML = ++t;
}
function go1()
{
document.getElementById("P1").hidden= true;
document.getElementById("P2").hidden = false;
}
function verify1()
{
document.getElementById("P2").hidden = true;
document.getElementById("result").hidden = false;
var correctAnswers= 0;
var question1 = document.getElementById("q1r3").checked;
if (question1 === true)
{
correctAnswers = correctAnswers + 1;
}
var question2 = document.getElementById("q2r4").checked;
if (question2 === true)
{
correctAnswers = correctAnswers + 1;
}
document.getElementById("resultado").innerHTML = correctAnswers + "/15" + " " + " correct" + " "+ "answers";
}
This is just a readonly. See the docs:
hidden
Is a Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.
What you must really do is:
document.getElementById("classic").style.display = 'none';
document.getElementById("quizr").style.display = 'block';
I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.
I am basically trying to have a word (page 2) be clickable and act as a link to display different div content. When they select option 2, then click the next button, they should be able to click "Page 2" test and cause that to display the id="test1" (Choice 1, Page 1) content. I have tried a few variables but haven't been able to get any to work. The best I could do is get it to take you back to the choice options, but I'd like to eliminate any users error and just go straight to the first page of the choice they should have made.
Any help would be grateful. And sorry, JQuery is not an option.
<!DOCTYPE html>
<html>
<center>
<head>
<title>Test2</title>
<script>
function formReset()
{
document.getElementById("home").innerHTML ="";
document.getElementById("main").style.display = 'block';
document.getElementById("1").checked = false;
document.getElementById("2").checked = false;
}
function nextPage()
{
if (document.getElementById("1").checked == true){
document.getElementById("home").innerHTML = document.getElementById("test1").innerHTML;
document.getElementById("main").style.display = 'none';
}
else
if (document.getElementById("2").checked == true){
document.getElementById("home").innerHTML = document.getElementById("test2").innerHTML;
document.getElementById("main").style.display = 'none';
}
return true;
}
function otherPage()
{
switch (document.getElementById('home').innerHTML)
{
case document.getElementById("test2").innerHTML:
(document.getElementById("home").innerHTML = document.getElementById("choice2_page2").innerHTML)
break;
}
}
</script>
</head>
<body>
<h1>This is a test of the radio buttons</h1>
<br />
<div>
<form>
<div id="home"></div>
<div id="main">
<input type="radio" name="grp1" id="1">1<br>
<input type="radio" name="grp1" id="2">2<br>
<br />
<input type="button" name="button" value="Next" onClick="nextPage()">
</div>
</form>
</div>
<div name="test1" id="test1" style="display:none"><!-- Display this content -->
<h2>Choice 1<br>Page 1</h2>
<input type="button" value="Reset" id="reset_form" onClick="formReset()">
</div>
<div name="test2" id="test2" style="display:none">
<h2>Choice 2<br>Page 1</h2>
<input type="button" value="Next" id="page_choice" onclick="otherPage()">
<input type="button" value="Reset" id="reset_form" onClick="formReset()">
</div>
<div name="choice2_page2" id="choice2_page2" style="display:none">
<h2>You should have chose<br><b>Choice 1</b></h2><!-- When clicked, this "Choice 1" should display the contents of id="test1" (Choice 1, Page 1)-->
<input type="button" value="Reset" id="reset_form" onClick="formReset()">
</div>
</body>
</center>
</html>
Okay, I think this is what you want, it may be a bit big, but it's a full solution for your problem, I guess. Mainly, you have some pages, the user may choose, which page to see first, but then you force the user to see all next pages one by one till the end. At least, it's what I did here.
You may add as much text pieces (pages) as you like in textContent array, just check that you have a corresponding number of radio buttons.
<html>
<head></head>
<body>
<div id="mainDiv" style="text-align: center">
<div id="textDiv"></div>
<div id="radioDiv">
<input type="radio" id="rad1" name="radGrp"><label for="rad1">1</label><br>
<input type="radio" id="rad2" name="radGrp"><label for="rad2">2</label><br>
<input type="radio" id="rad3" name="radGrp"><label for="rad3">3</label><br>
<input type="radio" id="rad4" name="radGrp"><label for="rad4">4</label><br>
<input type="radio" id="rad5" name="radGrp"><label for="rad5">5</label><br>
</div>
<div id="btnDiv">
<input type="button" id="btn" value="show"><br>
</div>
</div>
<script type="text/javascript">
/*here we push the onclick attribute in js, so the code is unobtrusive*/
document.getElementById("btn").onclick = function(){formContent();};
var radios = document.getElementsByName("radGrp"),
idCurrent = 0,
firstRun = true,
textContent = [
"<h3>option 1</h3><p>here is the text of option 1 :(</p>",
"<h3>option 2</h3><p>here is the text of option 2 :)</p>",
"<h3>option 3</h3><p>here is the text of option 3!</p>",
"<h3>option 4</h3><p>here is the text of option 4 :-D</p>",
"<h3>option 5</h3><p>here is the text of option 5 :-P</p>"
];
function hideDivs(){
document.getElementById("textDiv").style.display = "block";
document.getElementById("radioDiv").style.display = "none";
document.getElementById("btn").value = "next";
firstRun = false;
}
function restoreDivs(){
idCurrent=0;
document.getElementById("textDiv").style.display = "none";
document.getElementById("radioDiv").style.display = "block";
document.getElementById("btn").value = "show";
firstRun = true;
}
/*function to find the id of a checked radio from the group*/
function findChecked(){
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) idCurrent = radios[i].id;
}
/*since the id is in text, we cut the first part and leave*/
/*just the number*/
idCurrent = parseInt(idCurrent.slice(3));
}
/*actual function*/
function formContent(){
if (idCurrent == 0) findChecked();
if (firstRun) {
hideDivs();
}
/*pushing into textDiv values from textContent array, which*/
/*is your pages content*/
document.getElementById("textDiv").innerHTML = textContent[idCurrent - 1];
if (idCurrent<radios.length) {
idCurrent++;
/*changing the button value if the current piece of text*/
/*is the last one*/
} else if (idCurrent == radios.length) {
idCurrent++;
document.getElementById("btn").value = "finish!";
/*if there is no more text, we just restore everything to*/
/*the initial state*/
} else {
restoreDivs();
idCurrent = 0;
}
}
</script>
</body>
</html>
I think this is what you may be looking for
function showPage(id)
{
document.getElementById(id).style.display = 'block';
}
Choice 1
Ok, so here I've added consequent steps, that can be split into some categories (here: 3), if you select a step from some category, you will just read it. Hope that helps ;)
<html>
<head></head>
<body>
<div id="mainDiv" style="text-align: center">
<div id="textDiv"></div>
<div id="radioDiv">
<input type="radio" id="rad1" name="radGrp"><label for="rad1">1. reinstall os (step 1)</label><br>
<input type="radio" id="rad2" name="radGrp"><label for="rad2">2. reinstall os (step 2)</label><br>
<input type="radio" id="rad3" name="radGrp"><label for="rad3">3. reinstall os (step 3)</label><br>
<input type="radio" id="rad4" name="radGrp"><label for="rad4">4. reinstall os (step 4)</label><br>
<input type="radio" id="rad5" name="radGrp"><label for="rad5">5. watering a plant (step 1)</label><br>
<input type="radio" id="rad6" name="radGrp"><label for="rad6">6. watering a plant (step 2)</label><br>
<input type="radio" id="rad7" name="radGrp"><label for="rad7">7. reading alphabet (step 1)</label><br>
<input type="radio" id="rad8" name="radGrp"><label for="rad8">8. reading alphabet (step 2)</label><br>
<input type="radio" id="rad9" name="radGrp"><label for="rad9">9. reading alphabet (step 3)</label><br>
<input type="radio" id="rad10" name="radGrp"><label for="rad10">10. reading alphabet (step 4)</label><br>
</div>
<div id="btnDiv">
<input type="button" id="btn" value="show"><br>
</div>
</div>
<script type="text/javascript">
document.getElementById("btn").onclick = function(){formContent();};
var radios = document.getElementsByName("radGrp"),
idCurrent = 0,
planCurrent,
firstRun = true,
instructions = [
[0,1,2,3], /* your instruction plans */
[4,5], /* this is the second plan (with index = 1) and it has steps 5 and 6 */
[6,7,8,9] /* this is the third plan (with index = 2) and it has steps 7, 9, 9 and 10 */
],
textContent = [
"<h3>reinstall os (step 1)</h3><p>download .iso from torrent</p>",
"<h3>reinstall os (step 2)</h3><p>burn it to a cd of usb</p>",
"<h3>reinstall os (step 3)</h3><p>change bios settings</p>",
"<h3>reinstall os (step 4)</h3><p>boot, install, enjoy</p>",
"<h3>watering a plant (step 1)</h3><p>pour some water into a flask</p>",
"<h3>watering a plant (step 2)</h3><p>water the plant, enjoy</p>",
"<h3>reading alphabet (step 1)</h3><p>read letter \"a\"</p>",
"<h3>reading alphabet (step 2)</h3><p>read letter \"b\"</p>",
"<h3>reading alphabet (step 3)</h3><p>read letter \"c\"</p>",
"<h3>reading alphabet (step 4)</h3><p>read all the other letters, enjoy</p>"
];
function hideDivs(){
document.getElementById("textDiv").style.display = "block";
document.getElementById("radioDiv").style.display = "none";
document.getElementById("btn").value = "next";
firstRun = false;
}
function restoreDivs(){
document.getElementById("textDiv").style.display = "none";
document.getElementById("radioDiv").style.display = "block";
document.getElementById("btn").value = "show";
idCurrent=0;
firstRun = true;
}
/*function to find the id of a checked radio from the group*/
function findChecked(){
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) idCurrent = radios[i].id;
}
idCurrent = parseInt(idCurrent.slice(3))-1;
}
/*find which plan checked id belongs*/
function findPlan(){
for (var m=0;m<instructions.length;m++){
for (var n=0;n<instructions[m].length;n++){
if (instructions[m][n] == idCurrent) planCurrent = m;
}
}
}
/*actual function*/
function formContent(){
if (firstRun) {
findChecked();
findPlan();
hideDivs();
}
/*pushing into textDiv values from textContent array, which is your pages content*/
document.getElementById("textDiv").innerHTML = textContent[idCurrent];
/*check that we read just the current plan*/
if (idCurrent < instructions[planCurrent][instructions[planCurrent].length - 1]){
idCurrent++;
} else if (idCurrent == instructions[planCurrent][instructions[planCurrent].length - 1]) {
idCurrent++;
document.getElementById("btn").value = "finish!";
} else {
restoreDivs();
}
}
</script>
</body>
</html>