How to give h1div+1 after give correct answer? - javascript

I make a quiz with javascript and HTML. Now I want when you give a correct answer the h1divcirckel give plus 1. In my jsfiddle is the HTML and Javascript. The quiz doens't work in jsfiddle but it work in my website.
https://jsfiddle.net/aveLph7h/
<div id="cirkel">
<h1>145</h1>
</div>
<h1>Quiz</h1>
<div id='quiz'></div>
<div id='button'>Next</div>
And my javascript
var questions = [{
question: "Wie vinden zichzelf het lekkerst?",
choices: ["Vrouwen","Mannen"],
correctAnswer:0
}, {
question: "Wat doet meer pijn: wesp of bij?",
choices: ["wesp","bij"],
correctAnswer:0
},{
question: "What is 8*9?",
choices: [72,99,108,134,156],
correctAnswer:0
},{
question: "What is 1*7?",
choices: [4,5,6,7,8],
correctAnswer:3
},{
question: "What is 8*8?",
choices: [20,30,40,50,64],
correctAnswer:4
}];
function createQuestionElement(index) {
var qDiv = document.createElement('div');
qDiv.setAttribute('id','question');
var question = document.createElement('p');
question.innerHTML = questions[index].question;
qDiv.appendChild(question);
qDiv.appendChild(createRadios(index));
return qDiv;
}
function createRadios(index) {
var radioList = document.createElement('ul');
var str;
for(var i=0; i<questions[index].choices.length ; i++){
var item = document.createElement('li');
var input = '<input type="radio" name="answer" value=' + i
+ ' />';
input += questions[index].choices[i];
item.innerHTML =input;
radioList.appendChild(item);
}
return radioList;
}
var questionCounter = 0;
var numCorrect = 0;
var firstDiv = createQuestionElement(questionCounter);
$('#quiz').append(firstDiv);
var radios = document.getElementsByName('answer');
var button = document.getElementById('button');
$('#button').on('click', function() {
if(radios[questions[questionCounter].correctAnswer].checked){
numCorrect++;
}
questionCounter++;
$('#question').remove();
if(questionCounter<questions.length){
var nextDiv = createQuestionElement(questionCounter);
$('#quiz').append(nextDiv);
document.getElementById('quiz').appendChild(nextDiv);
} else {
document.getElementById('quiz').appendChild(displayScore());
}
});
function displayScore() {
var para = document.createElement('p');
para.innerHTML = 'Je hebt ' + numCorrect + ' vragen uit ' +
questions.length + ' goed!!!';
return para;
}
Hopefully can anybody help me.......

Do you mean that you just need to increment value in h1 tag?
If so I would do that this way by changing that part of code
if(radios[questions[questionCounter].correctAnswer].checked){
numCorrect++;
$('#cirkel h1').html(parseInt($('#cirkel h1').html(), 10) + 1);
}
working jsFiddle here https://jsfiddle.net/aveLph7h/1/

Related

Making a help bot that is in the bottom right corner

The website link The bot image I am making a website, and I have the chat parts, and some examples in the code, but I cant get a square, or an image, I need the image to be in a square, in the bottom left. And if there is any way to shorten it, please do so. The code snippet does work, but it says theres an error, this is already on my website.
$(function() {
var trigger = [
["hi","hey","hello"],
["how are you", "how is life", "how are things"],
["what are you doing", "what is going on"]
];
var reply = [
["Hi","Hey","Hello"],
["Fine", "Pretty well", "Fantastic"],
["Nothing much", "About to go to sleep", "Can you guest?", "I don't know actually"],
];
println('Bot: ' + trigger[1][0]);
var alternative = ["Haha...", "Eh..."];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'cds1170';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/ a /g, " ").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<span id="dir">Message: </span>
<div id="stretchbox">
<input type="text"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false">
</input>
</div>
</p>
</div>
<html>
<body>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<span id="dir">Message: </span>
<div id="stretchbox">
<input type="text"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false"
/>
</div>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
var trigger = [
["hi","hey","hello"],
["how are you", "how is life", "how are things"],
["what are you doing", "what is going on"]
];
var reply = [
["Hi","Hey","Hello"],
["Fine", "Pretty well", "Fantastic"],
["Nothing much", "About to go to sleep", "Can you guest?", "I don't know actually"],
];
println('Bot: ' + trigger[1][0]);
var alternative = ["Haha...", "Eh..."];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'cds1170';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/ a /g, " ").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
</script>
</body>
</html>

How do I display a function using setTimeout in JavaScript?

I have made a quiz with JavaScript and want that when the timer is up, it should not let you attempt the quiz anymore and go to the last page which displays the score. The score is displayed by calling displayResult. I have one HTML file and one JS file. When I use setTimeout, even after the time is up, it doesn’t show the score. I think the function doesn’t get called. I have tried using setInterval instead of setTimeout but still it doesn't work. Can someone tell me what I am doing wrong?
Whole code here.
//timer code in quiz.js
const startingMinutes = 1
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
if (time == 0) {
clearInterval(vri);
}
setTimeout(displayResult, 1000);
}
The function gets called you can easily check this by inserting a console.log() inside the function.
When you would like to display the results on the same page then first clear the body and append your new created element on the body.
There is still a bug that your selected elements will always be empty but I just answer your question here "How you display it."
For debugging purposes I set the timer to 6 seconds instead of 60.
(function() {
var allQuestions = [{
question: "The tree sends downroots from its branches to the soil is know as:",
options: ["Oak", "Pine", "Banyan", "Palm"],
answer: 2
}, {
question: "Electric bulb filament is made of",
options: ["Copper", "Aluminum", "lead", "Tungsten"],
answer: 3
}, {
question: "Non Metal that remains liquid at room temprature is",
options: ["Phophorous", "Bromine", "Clorine", "Helium"],
answer: 1
}, {
question: "Which of the following is used in Pencils ?",
options: ["Graphite", "Silicon", "Charcoal", "Phosphorous"],
answer: 0
}, {
question: "Chemical formula of water ?",
options: ["NaA1O2", "H2O", "Al2O3", "CaSiO3"],
answer: 1
}, {
question: "The gas filled in electric bulb is ?",
options: ["Nitrogen", "Hydrogen", "Carbon Dioxide", "Oxygen"],
answer: 0
}, {
question: "Whashing soda is the comman name for",
options: ["Sodium Carbonate", "Calcium Bicarbonate", "Sodium Bicarbonate", "Calcium Carbonate"],
answer: 0
}, {
question: "Which gas is not known as green house gas ?",
options: ["Methane", "Nitrous oxide", "Carbon Dioxide", "Hydrogen"],
answer: 3
}, {
question: "The hardest substance availabe on earth is",
options: ["Gold", "Iron", "Diamond", "Platinum"],
answer: 2
}, {
question: "Used as a lubricant",
options: ["Graphite", "Silica", "Iron Oxide", "Diamond"],
answer: 0
}];
var quesCounter = 0;
var selectOptions = [];
var quizSpace = $('#quiz');
nextQuestion();
$('#next').click(function() {
chooseOption();
if (isNaN(selectOptions[quesCounter])) {
alert('Please select an option !');
} else {
quesCounter += 5;
nextQuestion();
}
});
$('#prev').click(function() {
chooseOption();
quesCounter -= 5;
nextQuestion();
});
function createElement(index) {
var element = $('<div>', {
id: 'question'
});
var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>');
element.append(header);
var question = $('<p>').append(allQuestions[index].question);
element.append(question);
var radio = radioButtons(index);
element.append(radio);
var question1 = $('<p>').append(allQuestions[index + 1].question);
element.append(question1);
var radio1 = radioButtons1(index + 1);
element.append(radio1);
var question2 = $('<p>').append(allQuestions[index + 2].question);
element.append(question2);
var radio2 = radioButtons2(index + 2);
element.append(radio2);
var question3 = $('<p>').append(allQuestions[index + 3].question);
element.append(question3);
var radio3 = radioButtons3(index + 3);
element.append(radio3);
var question4 = $('<p>').append(allQuestions[index + 4].question);
element.append(question4);
var radio4 = radioButtons4(index + 4);
element.append(radio4);
return element;
}
function radioButtons(index) {
var radioItems = $('<ul>');
var item;
var input = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += allQuestions[index].options[i];
item.append(input);
radioItems.append(item);
}
return radioItems;
}
function radioButtons1(index) {
var radioItems1 = $('<ul>');
var item1;
var input1 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item1 = $('<li>');
input1 = '<input type="radio" name="answer1" value=' + i + ' />';
input1 += allQuestions[index].options[i];
item1.append(input1);
radioItems1.append(item1);
}
return radioItems1;
}
function radioButtons2(index) {
var radioItems2 = $('<ul>');
var item2;
var input2 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item2 = $('<li>');
input2 = '<input type="radio" name="answer2" value=' + i + ' />';
input2 += allQuestions[index].options[i];
item2.append(input2);
radioItems2.append(item2);
}
return radioItems2;
}
function radioButtons3(index) {
var radioItems3 = $('<ul>');
var item3;
var input3 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item3 = $('<li>');
input3 = '<input type="radio" name="answer3" value=' + i + ' />';
input3 += allQuestions[index].options[i];
item3.append(input3);
radioItems3.append(item3);
}
return radioItems3;
}
function radioButtons4(index) {
var radioItems4 = $('<ul>');
var item4;
var input4 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item4 = $('<li>');
input4 = '<input type="radio" name="answer4" value=' + i + ' />';
input4 += allQuestions[index].options[i];
item4.append(input4);
radioItems4.append(item4);
}
return radioItems4;
}
function chooseOption() {
selectOptions[quesCounter] = +$('input[name="answer"]:checked').val();
selectOptions[quesCounter + 1] = +$('input[name="answer1"]:checked').val();
selectOptions[quesCounter + 2] = +$('input[name="answer2"]:checked').val();
selectOptions[quesCounter + 3] = +$('input[name="answer3"]:checked').val();
selectOptions[quesCounter + 4] = +$('input[name="answer4"]:checked').val();
}
function nextQuestion() {
quizSpace.fadeOut(function() {
$('#question').remove();
if (quesCounter < allQuestions.length) {
var nextQuestion = createElement(quesCounter);
quizSpace.append(nextQuestion).fadeIn();
if (!(isNaN(selectOptions[quesCounter, quesCounter + 1, quesCounter + 2, quesCounter + 3, quesCounter + 4]))) {
$('input[value=' + selectOptions[quesCounter] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 1] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 2] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 3] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 4] + ']').prop('checked', true);
}
if (quesCounter === 1) {
$('#prev').show();
} else if (quesCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreRslt = displayResult();
quizSpace.append(scoreRslt).fadeIn();
$('#next').hide();
$('#prev').hide();
}
});
}
const startingMinutes = 0.1;
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
console.log(time);
if (time === 0) {
clearInterval(vri);
setTimeout(displayResult, 1000);
}
}
function displayResult() {
console.log(selectOptions);
var correct = 0;
console.log(selectOptions);
for (var i = 0; i < selectOptions.length; i++) {
if (selectOptions[i] === allQuestions[i].answer) {
correct++;
}
}
document.body.innerHTML = "";
let score = document.createElement("p");
score.id = 'question';
if (correct === 0 && correct <= 5) {
let otherText = document.createTextNode("YOUR IQ SCORES LIES IN THE RANGE OF 70 and 79 WHICH IS CLASSIFIED AS BORDERLINE");
let img = document.createElement("img");
img.src = "img9b.png"
score.append(otherText)
score.append(img);
} else {
let tex = document.createTextNode("The Result is: " + correct);
score.appendChild(tex);
}
document.body.appendChild(score);
}
})();
<html>
<head>
<title>Make Quiz Website</title>
<link rel="stylesheet" href="quiz.css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Quiz Website Using JavaScript</h1>
<br/>
<div id="quiz"></div>
<p id="countdown">30:00</p>
</h1>
<div class="button" id="next">Next</div>
<div class="button" id="prev">Prev</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="quiz.js"></script>
</body>
</html>

I have a button group for a school translator project but i cant get my buttons to work?

var EnglishDictionary = ["Pants", "Pencil Sharpener", "Lampshade", "Pillow", "Hat", "Speaker", "Blueberry", "Strawberry", "Banana", "Starfruit", "Apple", "Mango", "Peach", "Where am I?", "How are you?", "Hello, Whats your name?", "Where is the bathrooom?", "How do I get Home?", "Where is the Resturaunt?"];
var DutchDictionary = ["overhemd", "broek", "puntenslijper", "lampschaduw", "hoofdkussen", "hoed", "spreker", "Bosbes", "Aardbei", "banaan", "stervrucht", "appel", "Mango", "Perzik", "waar ben ik?", "hoe gaat het met je?", "Hallo hoe heet je?", "Waar is de badkamer?", "Hoe kom ik thuis?", "Waar is het toilet?"];
var wordImages = ["Pants.jpg", "Pencil Sharpener.jpg", "Lampshade.jpg", "Pillow.jpg", "Hat.jpg", "Speaker.jpg", "Blueberry.jpg", "Strawberry.jpg", "Banana.jpg", "Starfruit.jpg", "Apple.jpg", "Mango.jpg", "Peach.jpg", "Where am I.jpg", "How are you.jpg", "Hello, What is your name.jpg", "Where is the Bathroom.jpg", "How do I get home.jpg", "Where is the Resturaunt.jpg"];
var wordIndex;
var translatedWord;
var selectedImage;
var displayImage;
var findWord;
var findImage;
function translateWord(word) {
translatedWord = findWord(word);
selectedImage = findImage(word);
document.getElementById("output").value += " " + translatedWord;
displayImage = document.getElementById("displayImages").checked;
if (displayImage == true) {
document.getElementById("image").src = selectedImage;
}
}
function findWord(word) {
for (wordIndex in EnglishDictionary) {
if (word == EnglishDictionary[wordIndex]) {
return DutchDictionary[wordIndex];
}
}
}
function findImage(word) {
for (wordIndex in EnglishDictionary) {
if (word == EnglishDictionary[wordIndex]) {
return wordImages[wordIndex];
}
}
}
<button onclick="translateWord('Pillow')" class="button">Pillow</button>
<input type="text" id="output">
<input type="checkbox" id="displayImages">
<img id="image" src="" />
This my javascript for a button group but when ever I press the button nothing works, I keep getting
Uncaught ReferenceError: translateWord is not defined
What does this mean and how can I fix it. Thanks. This is for a school project.
your script tag has a typo "javasript". it should be javascript
<script type="text/javascript">
var EnglishDictionary = ["Pants","Pencil Sharpener","Lampshade","Pillow","Hat","Speaker","Blueberry","Strawberry","Banana","Starfruit","Apple","Mango","Peach","Where am I?","How are you?","Hello, Whats your name?","Where is the bathrooom?","How do I get Home?","Where is the Resturaunt?"];
var DutchDictionary = ["overhemd","broek","puntenslijper","lampschaduw","hoofdkussen","hoed","spreker","Bosbes","Aardbei","banaan","stervrucht","appel","Mango","Perzik","waar ben ik?","hoe gaat het met je?","Hallo hoe heet je?","Waar is de badkamer?","Hoe kom ik thuis?","Waar is het toilet?"];
var wordImages = ["Pants.jpg","Pencil Sharpener.jpg","Lampshade.jpg","Pillow.jpg","Hat.jpg","Speaker.jpg","Blueberry.jpg","Strawberry.jpg","Banana.jpg","Starfruit.jpg","Apple.jpg","Mango.jpg","Peach.jpg","Where am I.jpg","How are you.jpg","Hello, What is your name.jpg","Where is the Bathroom.jpg","How do I get home.jpg","Where is the Resturaunt.jpg"];
var wordIndex;
var translatedWord;
var selectedImage;
var displayImage;
var findWord;
var findImage;
function translateWord(word)
{ alert(2)
translatedWord = findWord(word);
selectedImage = findImage(word);
document.getElementById("output").value += " " + translatedWord;
displayImage = document.getElementById("displayImages").checked;
if (displayImage == true)
{
document.getElementById("image").src = selectedImage;
}
}
function findWord(word)
{
for (wordIndex in EnglishDictionary)
{
if (word == EnglishDictionary[wordIndex])
{
return DutchDictionary[wordIndex];
}
}
}
function findImage(word)
{
for (wordIndex in EnglishDictionary)
{
if (word == EnglishDictionary[wordIndex])
{
return wordImages[wordIndex];
}
}
}
</script>
<button onclick= "translateWord('Pillow')" class="button">Pillow</button>

Repopulating objects with a click

I'm attempting to repopulate my radio buttons with the next question that is stored in my array. I'm unsure of how to remove the current question and repopulate the radio buttons with the next question.
var questionsArray = [];
//Create counters for both correct answers and current question
var correctAnswers = 0;
var currentQuestion = 0;
//Contructor Function to create questions
function Question (question, choices, answer){
this.question = question;
this.choices = choices;
this.answer = answer;
}
//Question Creations
questionsArray.push(new Question(...
To append the questions to my radio buttons I've used this code:
$('.q_question').append(questionsArray[0]['question']);
//In order to be able to check what radio is click you have to change to value of the radio buttons to the correct answer.
$('.btn1').after(questionsArray[0]['choices'][0]);
$('.btn1').val(questionsArray[0]['choices'][0]);
$('.btn2').after(questionsArray[0]['choices'][1]);
$('.btn2').val(questionsArray[0]['choices'][1]);
$('.btn3').after(questionsArray[0]['choices'][2]);
$('.btn3').val(questionsArray[0]['choices'][2]);
$('.btn4').after(questionsArray[0]['choices'][3]);
$('.btn4').val(questionsArray[0]['choices'][3]);
To check the answers I've got with:
$('#submit').on('click', function(){
currentQuestion ++;
var answer = $('input[name="1"]:checked').val(); //By creating the answer variable we are able to store which radio button value is submitted.
if(answer == questionsArray[0]['answer']){
correctAnswers ++;
$('.jumbotron').append(answer + "?<br><br> That's correct! You have " + correctAnswers + " out of 10 correct!");
} else {
$('.jumbotron').append(answer+ "? <br><br> Oh dear, that's so so wrong! You have " + correctAnswers + " out of 10 correct");
}
return false;
});
I'm totally stuck now.
Here's an example of something you could do: Fiddle
Create a function to populate the question and options. Add <span> or <label> elements and change the html in them instead of just using .after().
function populateQuestion(index) {
$('.q_question').html(questionsArray[index]['question']);
for (var i = 0; i < 4; i++) {
$('.jumbotron').html('');
$('.btn' + (i + 1)).val(questionsArray[index]['choices'][i]).prop('checked', false);
$('.label' + (i + 1)).html(questionsArray[index]['choices'][i]);
}
}
Add an event listener for the "Continue" button that runs the function with the correct (updated) index:
$('.continue').on('click', function() {
populateQuestion(++currentQuestion);
});
Just be sure to remove currentQuestion++ from your submit handler.
I had the urge to restructure the questionnaire, so here is my proposal:
var questions = [];
questions.push({
question: "What does HTML stand for?",
choices: [
"Hyper Text Markup Language",
"High Text Main Language",
"Hyper Translated Modern Language"
],
answer: 0
});
questions.push({
question: "What does CSS stand for?",
choices: [
"C-Style-Source",
"Cascading Style Source",
"Cascading Style Sheets"
],
answer: 2
});
questions.push({
question: "What does JS stand for?",
choices: [
"JavaSource",
"JavaScript",
"JavaStuff"
],
answer: 1
});
// create question elements
for (var i = 0; i < questions.length; i++) {
var question = $('<div>').addClass('question');
question.append(
$('<div>').addClass('caption').text(questions[i].question)
);
var choices = $('<ul>').addClass('choices');
for (var n = 0; n < questions[i].choices.length; n++) {
var choice = $('<li>').addClass('choice');
choice.append(
$('<input>').attr('type', 'radio').attr('name', 'question' + i).val(n).attr('id', 'label_question' + i + '_' + n)
);
choice.append(
$('<label>').attr('for', 'label_question' + i + '_' + n).text(questions[i].choices[n])
);
choices.append(choice);
}
question.append(choices);
$('.questions').append(question);
}
// attach evaluation of answers
$('#submit').click(function() {
var result = $('#result');
var correctAnswers = 0;
for (var i = 0; i < questions.length; i++) {
if ( $('input[name="question' + i + '"]:checked').val() == questions[i].answer ) {
correctAnswers += 1;
}
}
result.text('You answered ' + correctAnswers + ' of ' + questions.length + ' questions correctly.').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="questions">
</div>
<button id="submit" type="button">
check answers
</button>
<div id="result" style="display: none;">
</div>

Matching radio button selection with nested Array content in Javascript

UPDATE 6-25-2014
Any insight would be appreciated!
UPDATE 6-21-2014
I tried to make the radio variables, global so the 'if block' in the 'answerFwd' function could be compared to the correctAnswer Array, but that didn't work!
UPDATE 6-16-2014
ADDED JS FIDDLE
I am building a quiz and creating an array of radio buttons dynamically, and would like to match the selected button with the correct answer I have established in the question array.
html
<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Observers</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">The Watchers </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">The Sentinels</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Oa</div>
</div>
questions:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];
var item = allQuestions[0];
var currentQuestion = 0;
var playersScore = 0;
//function which creates the buttons
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses");
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
ar radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var playerTally = 0; //Updated 6-9-2014
var playerFeedback = " "; //Updated 6-9-2014
var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
* Updated 6-9-2014 I am stumped; This doesn't work but I was encouraged I got a score tally on the page! Am I comparing the elements correctly? Updated 6-21-2014 This reversed the gain, where I had the tally render on the screen*
if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
playerTally += 1;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
}
At first I tried to debug this but had trouble finding where the error was coming from.
One thing I noticed was currentAnswer variable was only being set once. (when it was declared)
Another thing that would make this cleaner is storing each response to each question as a property of the questions object.
For example: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}
This is a good example of why you may want to use object oriented programming. You can keep the global namespace clean, while also having tighter control over your variables.
I put together this Quiz Code using some object oriented principles:
JavaScript
var Quiz = function(questions) {
this.questions = questions;
this.$template = {
"header": document.querySelector(".question"),
"options": document.querySelector(".question-choices")
};
this.init();
}
Quiz.prototype = {
"init": function() {
this.question = 0;
this.generateQuestion();
this.bindEvents();
},
//gets called when this.question == this.questions.length, calculates a score percentage and alerts it
"score": function() {
var correctCount = 0;
this.questions.forEach(function(question){
if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
})
alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
},
//Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
"generateQuestion": function() {
var question = this.questions[this.question];
this.$template.header.innerHTML = question.question;
this.$template.options.innerHTML = "";
question.choices.forEach(this.createRadio.bind(this));
},
//Binds the previous, and next event handlers, to navigate through the questions
"bindEvents": function() {
var _this = this,
$nextBtn = document.querySelector(".question-navigation--next"),
$prevBtn = document.querySelector(".question-navigation--prev");
$nextBtn.addEventListener("click", function(e) {
//Go to the next question
_this.question++;
if ( _this.question == _this.questions.length ) {
_this.score();
} else {
_this.generateQuestion();
}
});
$prevBtn.addEventListener("click", function(e) {
_this.question--;
if ( _this.question <= 0 ) _this.question = 0
_this.generateQuestion();
});
},
//Create each individual radio button, is callback in a forEach loop
"createRadio": function(choice, index) {
var question = this.questions[this.question];
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "options";
radio.id = "option-"+index;
if ( question.selectedAnswer === index ) {
radio.checked = true;
}
radio.addEventListener("click", function(e) {
question.selectedAnswer = index;
})
var radioText = document.createElement("label");
radioText.setAttribute("for", "option-"+index)
radioText.innerHTML = choice;
radioText.insertBefore(radio, radioText.firstChild);
this.$template.options.appendChild(radioText);
}
}
var q = new Quiz(allQuestions)

Categories

Resources