I have been working on a quiz application and I ran into a problem. My goal is to make the button show when the check button is clicked but it just won't work.
var pos = 0,
test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["What is num equal to?", "6", "5", "Potato", "A", "A Variable is something that can store data, like a number or a String (Some text). They can be written as an int or as a string. EXAMPLE: ", "https://s1.postimg.org/nqvwnr0un/Untitled.png"],
["What is 7 x 3?", "21", "24", "25", "A"],
["What is 8 / 2?", "10", "2", "4", "C"]
];
function _(x) {
return document.getElementById(x);
}
function renderQuestion() {
test = _("test_q");
text = _("test_t");
if (pos >= questions.length) {
test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " questions correct</h2>";
_("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
var BarPercent = (100 / questions.length) * (pos + 1);
var pb = document.getElementById("pb");
pb.style.width = BarPercent + "%";
var qresult = false;
function showResult(correct) {
if (correct === true) {
document.getElementById("Result").style.visibility = "visible";
}
}
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
info = questions[pos][5];
if (questions[pos][6] !== undefined) {
img = questions[pos][6];
} else {
img = ""
}
test.innerHTML = "<h4 style='color: #DDD;'>" + info + "</h3><br><img src='" + img + "' style='align: center; width: 50%;'>";
test.innerHTML += "<h3>" + question + "</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> " + chA + "<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> " + chB + "<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> " + chC + "<br><br>";
test.innerHTML += "<button id='sub_button'style='color: green; background-color: #CCC; border: 0px; width: 100%; text-align: left; font-weigth: 100px; font-size: 70px; border-radius: 20px;' onclick='checkAnswer()'>Check</button>";
}
function checkAnswer() {
choices = document.getElementsByName("choices");
for (var i = 0; i < choices.length; i++) {
if (choices[i].checked) {
choice = choices[i].value;
}
}
if (choice == questions[pos][4]) {
correct++;
qresult = true;
showResult(qresult);
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
div {
border-radius: 20px;
}
#test_q {
background-color: #AAA;
padding: 10px 40px 40px 40px;
}
body {
font-family: sans-serif;
background-color: AAA;
color: #EEE;
}
#pbc {
width: 100%;
height: 16px;
background: #444;
border-radius: 10px;
margin-bottom: 20px;
}
#pbc>#pb {
position: relative;
top: 0px;
background: #1D4;
width: 0%;
height: 16px;
color: #0FF;
text-align: center;
border-radius: 10px;
}
#Result {
margin-top: 150px;
width: 100%;
height: 100px;
max-height: 100px;
background-color: lightgreen;
position: absolute;
margin-bottom: 25px;
border-radius: 20px;
border: 0px;
visibility: hidden;
}
#result {
color: green;
text-align: left;
margin-left: 20px;
}
<div id="pbc">
<div id="pb">
</div>
</div>
<div id="test_q"></div>
<button id="Result" onclick="renderQuestion()">
<h1 id="result"></h1>
</button>
I've just changed some of your own code,
Try this:
var pos = 0,
test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["What is num equal to?", "6", "5", "Potato", "A", "A Variable is something that can store data, like a number or a String (Some text). They can be written as an int or as a string. EXAMPLE: ", "https://s1.postimg.org/nqvwnr0un/Untitled.png"],
["What is 7 x 3?", "21", "24", "25", "A"],
["What is 8 / 2?", "10", "2", "4", "C"]
];
function _(x) {
return document.getElementById(x);
}
function renderQuestion() {
test = _("test_q");
text = _("test_t");
if (pos >= questions.length) {
test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " questions correct</h2>";
document.getElementById("result").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
var BarPercent = (100 / questions.length) * (pos + 1);
var pb = document.getElementById("pb");
pb.style.width = BarPercent + "%";
var qresult = false;
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
info = questions[pos][5];
if (questions[pos][6] !== undefined) {
img = questions[pos][6];
} else {
img = ""
}
test.innerHTML = "<h4 style='color: #DDD;'>" + info + "</h3><br><img src='" + img + "' style='align: center; width: 50%;'>";
test.innerHTML += "<h3>" + question + "</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> " + chA + "<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> " + chB + "<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> " + chC + "<br><br>";
test.innerHTML += "<button id='sub_button'style='color: green; background-color: #CCC; border: 0px; width: 100%; text-align: left; font-weigth: 100px; font-size: 70px; border-radius: 20px;' onclick='checkAnswer()'>Check</button>";
}
function showResult(correct) {
if (correct === true) {
document.getElementById("Result").style.display = "block";
}
}
function checkAnswer() {
choices = document.getElementsByName("choices");
for (var i = 0; i < choices.length; i++) {
if (choices[i].checked) {
choice = choices[i].value;
}
}
if (choice == questions[pos][4]) {
correct++;
qresult = true;
showResult(qresult);
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
div {
border-radius: 20px;
}
#test_q {
background-color: #AAA;
padding: 10px 40px 40px 40px;
}
body {
font-family: sans-serif;
background-color: AAA;
color: #EEE;
}
#pbc {
width: 100%;
height: 16px;
background: #444;
border-radius: 10px;
margin-bottom: 20px;
}
#pbc>#pb {
position: relative;
top: 0px;
background: #1D4;
width: 0%;
height: 16px;
color: #0FF;
text-align: center;
border-radius: 10px;
}
#Result {
margin-top: 150px;
width: 100%;
height: 100px;
max-height: 100px;
background-color: lightgreen;
position: absolute;
margin-bottom: 25px;
border-radius: 20px;
border: 0px;
display: none;
}
#result {
color: green;
text-align: left;
margin-left: 20px;
}
<div id="pbc">
<div id="pb">
</div>
</div>
<div id="test_q"></div>
<button id="Result" onclick="renderQuestion()">
<h1 id="result"></h1>
</button>
Related
I'm trying to make a text encryptor page as my first developing challenge using HTML, CSS, and JS
Task
Make an <input type="button"> copying a text output from a <p> that's displayed on the screen showing the result of the Encryption or Decryption of an input text written by the user in a <textarea>.
Main problem
I honestly don't know how to do it, and I've not found any question or reply about how to make the function of copying output text outside of a <textarea> giving this function to an input button through Javascript.
Side problem
I've actually used the <button> HTML tag but for the deleting button (the little red one displayed on the page) and it works, but at the cost of not applying its given CSS styles. I appreciate it if someone who knows why this happens tells me why.
Things I tried
I've been looking for options to do so but I've crossed paths with things I have no idea such as "async", "navigation" or "exeCommand". The point is I've tried some of these but most of the Internet examples I've found are using the HTML tag and not`, which is what my challenge asks me for.
The Code
var botonEncriptador = document.querySelector(".btnEncrypt");
var botonDesencriptador = document.querySelector(".btnDesCrypt");
var botonCopiar = document.getElementById("copyButton");
var dollNotFound = document.querySelector(".msgMissDoll");
var msgNonExist = document.querySelector(".msgMissH2");
var inTxtEnDes = document.querySelector(".insertTxtEnDes");
var txtFinale = document.querySelector("#encryptResult");
botonEncriptador.onclick = funcionEncriptar;
botonDesencriptador.onclick = funcionDesencriptar;
function funcionEncriptar() {
ocultarElementos();
txtFinale.textContent = encriptarMensaje(recuperarContenido());
// Or:
// var area = recuperarContenido();
// txtFinale.textContent = encriptarMensaje(area);
//P.D.: var "area" here is a local var of "funcionEncriptar", it is not the same one
//from down there at "recuperarContenido" function.
}
function funcionDesencriptar() {
ocultarElementos();
txtFinale.textContent = desencriptarMensaje(recuperarContenido());
}
function borrarTextoArea() {
document.getElementById("areaInput").value = "";
//This function applies directly to the HTML button using the <button> tag.
}
function recuperarContenido() {
var area = document.getElementById("areaInput");
return area.value;
}
function ocultarElementos() {
dollNotFound.classList.add("hideElement");
msgNonExist.classList.add("hideElement");
inTxtEnDes.classList.add("hideElement");
}
function encriptarMensaje(mensaje) {
var textoIngresado = mensaje;
var textoFinale = "";
for (var i = 0; i < textoIngresado.length; i++) {
if (textoIngresado[i] == "a") {
textoFinale = textoFinale + "ai";
} else if (textoIngresado[i] == "e") {
textoFinale = textoFinale + "enter";
} else if (textoIngresado[i] == "i") {
textoFinale = textoFinale + "imes";
} else if (textoIngresado[i] == "o") {
textoFinale = textoFinale + "ober";
} else if (textoIngresado[i] == "u") {
textoFinale = textoFinale + "ufat";
} else {
textoFinale = textoFinale + textoIngresado[i];
}
}
return textoFinale;
}
function desencriptarMensaje(mensaje) {
var textoIngresado = mensaje;
var textoFinale = "";
for (var i = 0; i < textoIngresado.length; i++) {
if (textoIngresado[i] == "a") {
textoFinale = textoFinale + "a";
i = i + 1;
} else if (textoIngresado[i] == "e") {
textoFinale = textoFinale + "e";
i = i + 4;
} else if (textoIngresado[i] == "i") {
textoFinale = textoFinale + "i";
i = i + 3;
} else if (textoIngresado[i] == "o") {
textoFinale = textoFinale + "o";
i = i + 3;
} else if (textoIngresado[i] == "u") {
textoFinale = textoFinale + "u";
i = i + 3;
} else {
textoFinale = textoFinale + textoIngresado[i];
}
}
return textoFinale;
}
* {
margin: 0;
/*universal setting for no body margins*/
padding: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
body {
color: black;
background-image: url("imgs/schoolclassjpgversion.jpg");
background-size: cover;
}
header {
width: 100%;
/*Occupy the entire width of the page*/
height: 60px;
background-color: rgba(240, 240, 250, 1.0);
}
.logoAluraHdr {
padding-top: 5.5px;
}
main {
width: 100%;
height: 90%;
/*background-color: rgb(185, 255, 92);*/
display: flex;
justify-content: space-between;
}
section {
width: 40%;
height: 100%;
/*background-color: rgb(101, 92, 228);*/
}
.sect1 {
width: 70%;
}
#areaInput {
width: 80%;
height: 70%;
display: block;
margin: auto;
margin-top: 5%;
resize: none;
background-color: rgba(255, 253, 253, 0.754);
}
.encryptButtons {
text-align: center;
}
.btnEncrypt,
.btnDesCrypt {
width: 25%;
height: 45px;
margin-top: 10px;
font-weight: bolder;
color: #FFFFFF;
background-color: #0A3871;
transition: 2s all;
cursor: pointer;
}
.btnEncrypt:hover,
.btnDesCrypt:hover {
border-color: #fff710;
background: #3576c5;
}
.btnEncrypt:active,
.btnDesCrypt:active {
background: #3ac7c5;
transition: none;
}
.btnDeleTxt {
display: block;
margin: auto;
margin-top: 10px;
padding: 5px 10px;
font-weight: bolder;
color: #FFFFFF;
background: #ca1414;
border: 1px solid #000000;
border-radius: 30px;
transition: 1s all;
}
.btnDelTxt:hover {
background: #e33d3d;
border-color: #FFFFFF;
}
/*From here the styles for the right section of the page begin*/
.sect2 {
width: 25%;
text-align: center;
background-color: white;
border: 1px solid black;
border-radius: 10px;
margin-right: 20px;
box-sizing: border-box;
overflow: hidden;
}
.msgMissDoll {
width: 100%;
height: 60%;
padding-top: 50px;
box-sizing: border-box;
}
.msgMissH2 {
width: 100%;
height: 20%;
}
.insertTxtEnDes {
width: 100%;
height: 20%;
}
.encryptResCont {
width: 100%;
height: 70%;
padding: 30px;
box-sizing: border-box;
}
#secretMsgHdr {
/*Default style of H2 didn't apply well, so I added this*/
font-size: 24px !important;
font-weight: bold !important;
}
.copyBtnCont {
width: 100%;
height: 20%;
}
#copyButton {
width: 30%;
height: 45px;
display: block;
margin: auto;
}
footer {
width: 100%;
height: 60px;
background-color: rgba(240, 240, 250, 0.9);
}
.copyright {
text-align: center;
font-weight: bolder;
padding-top: 20px;
}
.hideElement {
display: none;
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="newStyle.css">
<title>Challenge Alura ONE #1 - Encriptor</title>
</head>
<body>
<header>
<img src="imgs/LogoOGLog.svg" alt="Small Alura's logo" class="logoAluraHdr">
</header>
<main>
<section class="sect1">
<textarea id="areaInput" placeholder="Escríbeme por aquí"></textarea>
<div class="encryptButtons">
<input type="button" class="btnEncrypt" value="Encríptalo">
<input type="button" class="btnDesCrypt" value="Desencríptalo">
</div>
<div id="deleteCont">
<input type="button" class="btnDeleTxt" value="Borrar" onclick="javascript:borrarTextoArea();">
</div>
</section>
<section class="sect2">
<div class="msgMissDoll">
<img src="imgs/MuñecologoDollAl.png" alt="Personaje animado lupa en mano no halla mensaje encriptado">
</div>
<div class="msgMissH2">
<h2>Message not found</h2>
</div>
<div class="insertTxtEnDes">
<p>Insert the text you want to Encrypt or Decrypt</p>
</div>
<div class="encryptResCont">
<h2 id="secretMsgHdr">Secret message:</h2>
<p id="encryptResult"></p>
</div>
<div class="copyBtnCont">
<input type="button" id="copyButton" value="Copiar">
</div>
</section>
</main>
<footer>
<p class="copyright">© Alura Latam - All rights reserved</p>
</footer>
<script src="logic.js"></script>
</body>
</html>
Just use addEventListener to listen to the click event so when the button is clicked you can retrieve the text content of the encrypted result.
Try the following:
botonCopiar.addEventListener('click', event => {
console.log(txtFinale.textContent)
})
All the new JavaScript code would be:
var botonEncriptador = document.querySelector(".btnEncrypt");
var botonDesencriptador = document.querySelector(".btnDesCrypt");
var botonCopiar = document.getElementById("copyButton");
var dollNotFound = document.querySelector(".msgMissDoll");
var msgNonExist = document.querySelector(".msgMissH2");
var inTxtEnDes = document.querySelector(".insertTxtEnDes");
var txtFinale = document.querySelector("#encryptResult");
botonEncriptador.onclick = funcionEncriptar;
botonDesencriptador.onclick = funcionDesencriptar;
botonCopiar.addEventListener('click', event => {
console.log(txtFinale.textContent)
})
function funcionEncriptar() {
ocultarElementos();
txtFinale.textContent = encriptarMensaje(recuperarContenido());
// Or:
// var area = recuperarContenido();
// txtFinale.textContent = encriptarMensaje(area);
//P.D.: var "area" here is a local var of "funcionEncriptar", it is not the same one
//from down there at "recuperarContenido" function.
}
function funcionDesencriptar() {
ocultarElementos();
txtFinale.textContent = desencriptarMensaje(recuperarContenido());
}
function borrarTextoArea() {
document.getElementById("areaInput").value = "";
//This function applies directly to the HTML button using the <button> tag.
}
function recuperarContenido() {
var area = document.getElementById("areaInput");
return area.value;
}
function ocultarElementos() {
dollNotFound.classList.add("hideElement");
msgNonExist.classList.add("hideElement");
inTxtEnDes.classList.add("hideElement");
}
function encriptarMensaje(mensaje) {
var textoIngresado = mensaje;
var textoFinale = "";
for (var i = 0; i < textoIngresado.length; i++) {
if (textoIngresado[i] == "a") {
textoFinale = textoFinale + "ai";
} else if (textoIngresado[i] == "e") {
textoFinale = textoFinale + "enter";
} else if (textoIngresado[i] == "i") {
textoFinale = textoFinale + "imes";
} else if (textoIngresado[i] == "o") {
textoFinale = textoFinale + "ober";
} else if (textoIngresado[i] == "u") {
textoFinale = textoFinale + "ufat";
} else {
textoFinale = textoFinale + textoIngresado[i];
}
}
return textoFinale;
}
function desencriptarMensaje(mensaje) {
var textoIngresado = mensaje;
var textoFinale = "";
for (var i = 0; i < textoIngresado.length; i++) {
if (textoIngresado[i] == "a") {
textoFinale = textoFinale + "a";
i = i + 1;
} else if (textoIngresado[i] == "e") {
textoFinale = textoFinale + "e";
i = i + 4;
} else if (textoIngresado[i] == "i") {
textoFinale = textoFinale + "i";
i = i + 3;
} else if (textoIngresado[i] == "o") {
textoFinale = textoFinale + "o";
i = i + 3;
} else if (textoIngresado[i] == "u") {
textoFinale = textoFinale + "u";
i = i + 3;
} else {
textoFinale = textoFinale + textoIngresado[i];
}
}
return textoFinale;
}
I want to color the button with green when user choice the correct answer, and with red when it is wrong but in a same time with color the correct answer with green i try this but it is not work.
this text is to let me to publish the post
/*
I would like to be able to show the user what the correct answer to the question is if the one that they selected was incorrect. I would like to keep it simple, but here is what I am thinking. Once the user submits their answer and if it is incorrect, before moving onto the next question I would like for the incorrect answer to be highlighted in red, and the correct answer to be highlighted in green.
I already have coded whether or not the answer is correct or incorrect, but I haven't been able to figure out how to be able to show the correct answer if an incorrect one is chosen.
*/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
populateV2();
wait(2000);
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
document.getElementById("btn0").style.backgroundColor='green';
return this.answer === choice;
}
function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function populateV2() {
console.log("Test");
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
}
showProgress();
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.At what age was Harry Potter when he received his Hogwarts letter?",
["A: 9",
"B: 6",
"C: 7"],
["A", "B","C"],
"C"),
new Question("2.Which is not a Hogwarts house?",
["A: Dunder Mifflin",
"B: Ravenclaw",
"C: Slytherin"],
["A", "B","C"],
"A"),
new Question("3.Who teaches Transfiguration at Hogwarts?",
["A: Rubeus Hagrid",
"B: Minerva McGonnagle",
"C: Albus Dumbledore"],
["A", "B","C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 600px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 20px;
color: #5A6772;
}
.grid1 #textAnswer {
font-family: "monospace";
font-size: 15px;
color: #5A6772;
}
.image {
width: 20%;
}
.buttons {
margin-top: 30px;
}
#btn0, #btn1 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn2 {
background-color: #778897;
width: 500px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 20px;
padding: 10px 10px;
}
#btn0:hover, #btn1:hover, #btn2:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus, #btn1:focus, #btn2:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
In order to color the right choice with green and the wrong choices with red just select all buttons, compare the content of their <span> element with the right answer and color them accordingly:
function wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
populateV2();
wait(2000);
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
var answer = this.answer;
const buttons = document.querySelectorAll('button');
for (let i = 0; i < buttons.length; i++) {
var letter = buttons[i].getElementsByTagName("span")[0].textContent;
if (letter == answer) {
buttons[i].style.backgroundColor = 'green';
} else {
buttons[i].style.backgroundColor = 'red';
}
}
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for (var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function populateV2() {
console.log("Test");
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for (var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
}
showProgress();
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.At what age was Harry Potter when he received his Hogwarts letter?",
["A: 9",
"B: 6",
"C: 7"
],
["A", "B", "C"],
"C"),
new Question("2.Which is not a Hogwarts house?",
["A: Dunder Mifflin",
"B: Ravenclaw",
"C: Slytherin"
],
["A", "B", "C"],
"A"),
new Question("3.Who teaches Transfiguration at Hogwarts?",
["A: Rubeus Hagrid",
"B: Minerva McGonnagle",
"C: Albus Dumbledore"
],
["A", "B", "C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 600px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 20px;
color: #5A6772;
}
.grid1 #textAnswer {
font-family: "monospace";
font-size: 15px;
color: #5A6772;
}
.image {
width: 20%;
}
.buttons {
margin-top: 30px;
}
#btn0, #btn1 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn2 {
background-color: #778897;
width: 500px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 20px;
padding: 10px 10px;
}
#btn0:hover, #btn1:hover, #btn2:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus, #btn1:focus, #btn2:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
Note that you have to adjust/restructure your code so that there's a short waiting time before the new question is generated as I think you might want to show the buttons again with the grey background color upon a new question.
I have to create a "Quiz" and I have an array with 10 elements in it, and I am randomly selecting one as the correct answer, and I can't find a way so it doesn't generate it again, but instead sends the element to another array and removes it from the first one, so each time I click next question there is 1 less element in the starting array. Can anyone help? Here's what I've tried so far
var receivedArray = [{
nameIMGTOP: "15",
nameIMGTOPafter: "12",
nameIMGLEFT: "11",
nameIMGLEFTafter: "12",
nameTOP: "34"
},
{
nameIMGTOP: "-5",
nameIMGTOPafter: "-10",
nameIMGLEFT: "18",
nameIMGLEFTafter: "22",
nameTOP: "-3"
},
{
nameIMGTOP: "12",
nameIMGTOPafter: "",
nameIMGLEFT: "43",
nameIMGLEFTafter: "",
nameTOP: "29"
}
];
const StartElements = receivedArray;
var SelectedElements = [];
const correctAnswer = StartElements.splice(Math.floor(Math.random() * StartElements.length), 1)[0];
const guess1 = StartElements.splice(Math.floor(Math.random() * StartElements.length), 1)[0];
const guess2 = StartElements.splice(Math.floor(Math.random() * StartElements.length), 1)[0];
$("#btn-next").on("click", function() {
var i = 0;
while (i < correctAnswer.length) {
var item = correctAnswer[i];
console.log(item);
if (item.selected) {
correctAnswer.splice(i, 0);
SelectedElements.push(item);
} else i++;
console.log(SelectedElements);
}
});
$(document).ready(function() {
$("#test-div").append(
"<div class=\"row\">\n" +
"<div class=\"col-6\">\n" +
"<div class=\"ImageDiv\">" +
"<img id=\"testImage\" src=\"\" alt='...' align=\"middle\"/>\n" +
"</div>" +
"</div>\n" +
"<h4 class=\"Guess\" id=\"Guess\">ATMINI JŪRNIEKU MEZGLA NOSAUKUMU</h4>\n" +
"<p id=\"description\"></p>" +
"<div class=\"col-6 shuffle\">\n" +
"<div class=\"btn guesses\" >" + correctAnswer.nameLV + "</div><br>" +
"<div class=\"btn guesses\" >" + guess1.nameLV + "</div><br>" +
"<div class=\"btn guesses\" >" + guess2.nameLV + "</div><br>" +
"</div>\n" +
"</div>\n"
);
$("#testImage").attr("src", "../Images/uploads/" + correctAnswer.Image);
//$("#description").html(correctAnswer.descriptionLV);
console.log("Bwf");
$(".shuffle").each(function() {
var divs = $(this).find('div');
for (var i = 0; i < divs.length; i++) $(divs[i]).remove();
//the fisher yates algorithm, from http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array
var i = divs.length;
if (i == 0) return false;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = divs[i];
var tempj = divs[j];
divs[i] = tempj;
divs[j] = tempi;
}
for (var i = 0; i < divs.length; i++) $(divs[i]).appendTo(this);
});
});
#Guess {
color: #EEA774;
position: absolute;
top: 11vw;
left: 50vw;
}
.guesses {
background-color: #E89F62;
color: white;
font-weight: bolder;
border-radius: 20px;
width: 17vw;
text-align: left;
font-size: 20px;
margin-bottom: 10px;
display: flex;
flex-direction: column;
}
a {
color: #F3A361;
font-size: 25px;
}
a:active {}
ol {
padding-left: 50px;
}
.crumbItem {
margin-left: 200px;
}
.shuffle {
display: block;
color: white;
margin: 4px;
padding: 8px;
position: absolute;
top: 15vw;
left: 50vw;
}
#description {
position: absolute;
top: 13vw;
left: 50vw;
color: white;
width: 35vw;
font-size: 20px;
font-weight: bold;
}
#testImage {
display: block;
margin-left: auto;
margin-right: auto;
max-height: 700px;
}
.ImageDiv {
display: block;
margin-left: auto;
margin-right: auto;
}
#btn-next {
outline: none;
height: 40px;
border: none;
color: white;
text-align: center;
text-decoration: none;
font-size: 16px;
}
#btn-prev {
height: 40px;
border: none;
color: white;
text-align: center;
text-decoration: none;
font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="test-div" id="test-div">
<div class="btn" id="btn-prev" onclick=""><i class="fas fa-angle-left fa-3x"></i></div>
<div class="btn" id="btn-next" onclick=""><i class="fas fa-angle-right fa-3x"></i></div>
</div>
</div>
Everything is dynamically created basing off of the receivedArray
I am creating a quiz in Javascript but I want to replace my questions with images instead. i.e the logos of the programming languages. I have seen other examples but none to what I need. If anyone could help I would really appreciate it.
Sorry that snippet is not working, not use to it. I hope the code below helps expalin what I am asking
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
//populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
As York said, you need to upload/put the images to your server or get them from other URLs.
Next, you'll need to save them (probably in questions). In this example I used imgURL inside each Question.
Then use this code to show the image:
var element = document.getElementById("question");
element.innerHTML = '<img src=' + quiz.getQuestionIndex().imgURL + '" />'
I assume you mean this - replace the placeholder images with your own. The encodeURI was just because # and ++ are uri elements:
var images = {
"CSS" : "https://via.placeholder.com/200x50?text=CSS",
"HTML" : "https://via.placeholder.com/200x50?text=HTML",
"Java" : "https://via.placeholder.com/200x50?text=JAVA",
"C#" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("#"),
"C++" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("++"),
"C" : "https://via.placeholder.com/200x50?text=C"
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("<img src='https://via.placeholder.com/200x50?text=OOP' /><br/>Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("<img src='https://via.placeholder.com/200x50?text=Web+development' /><br/>Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
I have a function MultiChoiceQues(theSeq, theQues, theChoices theAns). I then add the theQues in a p tag followed by the unordered list of all the respective options with an input of type radio for each option.
In an array variable allQues[] I created multiple instance for the function MultiChoiceQues passing different arguments. Now, on load I'm showing all the questions with their respective options.
How can I access and highlight all the correct answers?
var content = "";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="' + theSeq + '"/> ' + eachChoice + '</li>';
});
content += '</ul>';
return content;
console.log(content);
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
];
function ShowAllQues() {
document.getElementById("container").innerHTML = content;
}
function ShowAllAns() {
/* Highlight all the correct answers */
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul {
list-style: none;
}
ul li:hover {
cursor: pointer;
color: #5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor: pointer;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus {
outline: 0;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns(); return false;">
</body>
Add the getAnswer method to your MultiChoiceQues constructor.
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
});
content+='</ul>';
this.getAnswer = function () {
return theAns;
}
}
Then this is your answers function.
function ShowAllAns(){
/* Highlight all the correct answers */
var answers = allQues.map(function (question) {
return question.getAnswer();
})
var question_lists = document.getElementById("container").getElementsByTagName('ul');
for (var i = 0; i < question_lists.length; i++) {
var answer_index = answers[i];
var items = question_lists[i].childNodes;
items[answer_index - 1].style.background = "red";
}
}
https://jsfiddle.net/1prr4m7f/3/
tl;dr:
Add Class <ul class="answerChoicesGroup">
Replace return content with this.answer = theAns;
Create var getting answerChoicesGroup: answerChoicesGroup = document.getElementsByClassName('answerChoicesGroup');
Insert in showAllAns() the following:
.
function ShowAllAns() {
/* Highlight all the correct answers */
for (i = 0; i < allQues.length; i++) {
// Get the current answer group
var answerGroup = answerChoicesGroup[i],
// Access the correct radio input answer by getting the answer index from `allQues`
correctAnswer = answerGroup.children[allQues[i].answer - 1];
// Do whatever you'd like with `correctAnswer`
correctAnswer.firstElementChild.checked = true;
correctAnswer.classList.add('answer');
}
}
Explanation
You are on the right track by return content. Instead of that, (which won't return content because you have the keyword new) I just did this.answer = theAns. answer can be any word you'd like.
The way to access answer would be like any object. i.e.
var muiltipleChoiceQuestion = new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
alert(muiltipleChoiceQuestion.answer) // result: 4
The next thing I did was, added a class name to all the ul's called answerChoicesGroup, and created a variable for that too.
In showAllAns() function, I iterated through allQues, and accessed the correct answer by:
Get the current answer group. (var answerGroup)
Access the correct radio input answer by getting the answer index from allQues. (var correctAnswer)
Do whatever you'd like with correctAnswer.
Here's the code:
Here's how you would do it:
JSFiddle
var content = "";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul class="answerChoicesGroup">';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="' + theSeq + '"/> ' + eachChoice + '</li>';
});
content += '</ul>';
this.answer = theAns;
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
],
answerChoicesGroup = document.getElementsByClassName('answerChoicesGroup');
function ShowAllQues() {
document.getElementById("container").innerHTML = content;
}
function ShowAllAns() {
/* Highlight all the correct answers */
for (i = 0; i < allQues.length; i++) {
// Get the current answer group
var answerGroup = answerChoicesGroup[i],
// Access the correct radio input answer by getting the answer index from `allQues`
correctAnswer = answerGroup.children[allQues[i].answer - 1];
// Do whatever you'd like with `correctAnswer`
correctAnswer.firstElementChild.checked = true;
correctAnswer.classList.add('answer');
}
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul {
list-style: none;
}
ul li:hover {
cursor: pointer;
color: #5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor: pointer;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus {
outline: 0;
}
.answer {
color: green;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns();">
</body>
Try this with jQuery:
var content="";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice,index) {
if(index == theAns-1){
content += '<li class="options answer"><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
}else{
content += '<li class="options"><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
}
});
content+='</ul>';
return content;
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
];
function ShowAllQues(){
document.getElementById("container").innerHTML=content;
}
function ShowAllAns(){
$(".answer").addClass("green");
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul{
list-style:none;
}
ul li:hover{
cursor:pointer;
color:#5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor:pointer;
}
.green{
color: #1B6F1B;
font-size: 18px;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus{
outline:0;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns();
return false;">