Making a quiz with Javascript. Getting array values from and object. - javascript

Im trying to create a simple quiz with Javascript. I am struggling to grasp the concept of how to iterate over the values of an array from an object. I eventually want to display a radio button with its value as the choice of answers. If someone could point me in the right direction i would really appreciate it.
Fiddle: http://jsfiddle.net/Renay/eprxgxhu/
Here is my code:
HTML
<h1> General Knowledge Quiz </h1>
<h2 id='questionTitle'> </h2>
<ul id ='selectionList'> </ul>
<p> Click the next button to go to the next question! </p>
<button type="button" id = nextButton> Next </button>
</div>
Javascript
var allQuestions = [{
question: 'What is the capital city of Australia?',
choices: ['Sydney', 'Melbourne', 'Canberra', 'London'],
correctAnswer: 2
},
{
question: 'Who won the 2014 FIFA World Cup?',
choices: ['Brazil', 'England', 'Germany', 'Spain'],
correctAnswer: 2
},
{
question: 'What book series is authored by J.K Rowling?',
choices: ['Game of Thrones', 'Hunger Games', 'Twilight', 'Harry Potter'],
correctAnswer: 3
},
{
question: 'The Eiffel Tower is located in which following country?',
choices: ['Italy', 'France', 'Iceland', 'Mexico'],
correctAnswer: 1
}];
//Reference to tags
var questionTitle = document.getElementById('questionTitle');
var selectionList = document.getElementById('selectionList');
var nextButton = document.getElementById('nextButton');
//Initiating some variables
var i = 0;
var length1 = allQuestions.length;
var correctAnswer = 0;
function populateQuestion() {}

Firstly attach click event to next button and give call to populateQuestion() using counter to iterate through allQuestions array and use i as counter variable.
nextButton.onclick = function() {
/*itterate through questions*/
if(i>allQuestions.length -1){/*go to first when reached last*/
i=0;
}
populateQuestion(i);
i++;
};
Iterate through allQuestions array for question title and choices as:
function populateQuestion(qNum) {
var individualQuestion = allQuestions[i];
questionTitle.innerText = individualQuestion.question;
selectionList.innerHTML = ""; //reset choices list
for(key in individualQuestion.choices){
var radioBtnName = "question"+i+"_choice";
var choiceText = individualQuestion.choices[key];
selectionList.appendChild(createLi(radioBtnName,choiceText));
}
}
Write dynamic li and radio button creation function as:
function createLi(name, choiceText) {
var e = document.createElement('li');
var radioHtml = '<input type="radio" name="' + name + '"';
radioHtml += '/>';
radioHtml += choiceText;
e.innerHTML = radioHtml;
return e;
}
Please refer to this fiddle for same.

You need to associate an onClick event with your button to call the relevant part of the JavaScript. Go through the example here
On another note, using JavaScript for a quiz might not be a good idea as one can see the answers using view-source. I would suggest using PHP to fetch results from a database.

Related

How to iterate over unique id names without hardcoding?

I am making a quiz. I would like to iterate over the different buttons to bring up different questions once I press the buttons. However, since each button has a different id, I am finding it difficult to find a way of changing the id names in the loop. See below for code:
let mybtn1 = document.getElementById("myBtn1")
let questions = [
{
question : "What is an Epidemics?",
choiceA : "CorrectA",
choiceB : "WrongB",
choiceC : "WrongC",
choiceD: "Hello",
correct : "Hello"
},{
question : "What does CSS stand for?",
choiceA : "Wrong",
choiceB : "Correct",
choiceC : "Wrong",
correct : "B"
},{
question : "What does JS stand for?",
choiceA : "Wrong",
choiceB : "Wrong",
choiceC : "Correct",
correct : "C"
}
];
mybtn1.addEventListener("click", pressbtn);
function pressbtn(){
modal.style.display = "block";
questionText.innerHTML = questions[0].question;
answerA.innerHTML = questions[0].choiceA;
answerB.innerHTML = questions[0].choiceB;
answerC.innerHTML = questions[0].choiceC;
answerD.innerHTML = questions[0].choiceD;
}
<ul class="path-one-row">
<li class="grid blue" id="myBtn1"></li>
<li class="grid blue" id="myBtn2"></li>
<li class="grid blue" id="myBtn3"></li>
<li class="grid blue" id="myBtn4"></li>
</ul>
For example, when I click the button with id='mybtn1', it should iterate to give me access to questions[0] and so then I can manipulate the innerHTML. For id='mybtn2', questions[1] and so on. How could I write a loop to help me iterate this?
You can just give the buttons the same class or data-attribute, and you can select them with querySelectorsAll and loop through, and with its index, you can iterate through.
For example all button has the data-question attribute.
Get them like
const questions = document.querySelectorsAll('[data-question]')
And loop through
questions.forEach((index) => {
question.addEventListener("click", () => pressbtn(index));
function pressbtn(index){
modal.style.display = "block";
questionText.innerHTML = questions[index].question;
answerA.innerHTML = questions[index].choiceA;
answerB.innerHTML = questions[index].choiceB;
answerC.innerHTML = questions[index].choiceC;
answerD.innerHTML = questions[index].choiceD;
}
})
Well, there are several ways to make that. Using vanilla javascript you can call a function when clicking a button, pass the id to the function and create the li with that data
<button id="0" click = changeButtons(id)>
<ul id="buttonList>
</ul>
//change buttons
changeButtons (id){
let list =document.getElementbyId(buttonList)
let questions = []
questions[id].forEach(question => {
list.innerHtml += <li><button> question</button> </li>
})
}
note that you have to alter your json to make an array with the questions, you also can use keys to make an array with your questions keys and access to that

Attempting to dynamcially append innerText to label elements from array

I am working on my second ever Javascript project. As you can imagine, since I am still finding my feet with building projects, there are quite a few errors which I am running into (and learning from).
Let me just quickly explain what stage I am at in building the family quiz and what the problem is. I have created an array of objects which stores questions, choices and answers within each index of the array.
When the quiz starts up, there is an intro screen displaying the rules etc. The user then clicks on a "start quiz" button which transitions the screen to the first question.
The user then selects the correct answer and clicks next question. This is the stage I am at currently.
What I am trying to simply do is append the next 'choices' into the label elements. But when I click it nothing happens. Obviously I am doing something wrong.
Please can someone assist?
Many thanks!
EDIT I have been informed by a response that there was a syntax error in my forEach loop which appends the next 'choices' to the label elements. I have corrected that. However, what I am finding now is that it is only appending the first index value of every 'choices' array to every label button.
$(document).ready(function(){
var azeem = [
{
question: "What is Azeem's favourte color?",
choices: ["blue", "yellow", "red", "green"],
answer: 0
},
{
question: "What is Azeem's favourte movie?",
choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
answer: 3
},
{
question: "What was Azeem's first ever job role?",
choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
answer: 1
},
{
question: "What is Azeem's favourite dish?",
choices: ["Pasta", "Pizza", "Chips", "Curry"],
answer: 0
},
{
question: "What subject did Azeem enjoy the most in school?",
choices: ["Drama", "Science", "P.E", "History"],
answer: 0
},
{
question: "What subject did Azeem least enjoy in school?",
choices: ["Geography", "Maths", "History", "I.T"],
answer: 1
},
{
question: "Which one of these cities has Azeem travelled to?",
choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
answer: 1
},
{
question: "Which college did Azeem study in?",
choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
answer: 3
},
{
question: "Who is Azeem's favourite sports icon?",
choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
answer: 1
},
{
question: "Who is Azeem's favourite music artist?",
choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
answer: 1
},
];
var currentQuestion = 0;
var questionNumberCounter = 1;
var questionNumber = document.getElementById("questionCount");
var choices = document.getElementById("choicesSection");
var questions = document.getElementById("ques");
questions.innerText = azeem[currentQuestion].question;
// The following event listener will transition from the instructions to the first question of the quiz
document.getElementById("startquiz").addEventListener("click",function(){
$(".quiz-intro").fadeOut(600);
$(".quiz-section").delay(600).slideDown("slow");
questionNumber.innerText = questionNumberCounter;
azeem[currentQuestion].choices.forEach(function(value){
var radio = document.createElement("input");
var label = document.createElement("label");
var div = document.createElement("div");
$(div).addClass("choice");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "answer");
radio.setAttribute("value", value);
var radioID = 'question-'+currentQuestion;
radio.setAttribute('id', radioID) ;
label.setAttribute("for", radioID);
label.innerHTML = value +"<br>";
choices.appendChild(div);
div.appendChild(radio);
div.appendChild(label);
})
})
document.getElementById("submitanswer").addEventListener("click",function(){
questionNumberCounter++;
questionNumber.innerText = questionNumberCounter;
currentQuestion++
questions.innerText = azeem[currentQuestion].question;
azeem[currentQuestion].choices.forEach(function(value){
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < 5){
labels[labelCounter].innerText = value;
labelCounter++;
}
}
})
});
HTML:
<div class="container">
<h1 class="text-center">FAMILY QUIZ</h1>
<h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>
<div class="row text-center quizSection">
<div class="col-md-4 image-section">
<img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
</div>
<div class="col-md-8 quiz-intro">
<h2>INSTRUCTIONS</h2>
<ul id="instructions">
<li>This is a multiple choice quiz</li>
<li>There is only one correct answer per question</li>
<li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>
<li>There are no hints available during the process of the quiz</li>
<li>Click the 'Start Quiz' button to begin</li>
</ul>
<button id="startquiz" class="btn-small btn-success">START QUIZ</button>
</div>
<div class="col-md-8 quiz-section">
<h5>Question <span id="questionCount">1</span> of 15</h5>
<p class="text-center" id="ques"></p>
<div id="choicesSection">
</div>
<input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">
</div>
</div>
Okay so first things first, you were missing a closing parens )
The bigger issue with your code lay within two things. First, this for loop is causing an issue where every choice you iterate over you are renaming every label that name. Why? The code below goes through each choice, sure, but it then loops over every label and redefines the label's text as that choice. Take a look:
azeem[currentQuestion].choices.forEach(function(value) {
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < 5) {
labels[labelCounter].innerText = value;
labelCounter++;
}
});
Another thing you'll notice above is that you are specifically saying 5 when really the operand should be checking for an amount that's less than labels.length (this will throw an error, so once we change it we can carry on)
azeem[currentQuestion].choices.forEach(function(value) {
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < labels.length) {
labels[labelCounter].innerText = value;
labelCounter++;
}
});
Now you'll see the questions populate with the same possible answer over and over. How do we fix this? Well, first it would pay to get our labels ahead of the loop since the elements themselves aren't being moved or deleted(we're just changing their text property) otherwise we're wasting resources grabbing the same elements over and over again.
Secondly forEach comes with a handy parameter called index that is automatically supplied to the callback function. a.e. forEach(item, indexOFItem) - this means that we can eliminate your while loop entirely and just change the label corresponding to the index of the choice.
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
Edit As pointed out in the comments, you're also going to want to check if the current question exists before loading it. A quick and dirty test for this with your current code is to simply check if the question exists in your object. There are better ways to make sure. You want to avoid static values when it comes to dynamic objects/arrays. As an example the labels issue above where you had set it to check if it was < 5 (less than 5). We changed this to labels.length to dynamically check the length instead of assuming it would always be 5. In the case of the question number, you have 15 questions stated, but that's not dynamic. A better way would be to check against azeem.length if you know that every object within azeem is a question. However, as I'm not sure, a quick fix is the following:
if (azeem[currentQuestion]) {
questions.innerText = azeem[currentQuestion].question;
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
} else {
alert("no more questions");
}
If you change these things the code will run as follows:
$(document).ready(function() {
var azeem = [{
question: "What is Azeem's favourte color?",
choices: ["blue", "yellow", "red", "green"],
answer: 0
}, {
question: "What is Azeem's favourte movie?",
choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
answer: 3
}, {
question: "What was Azeem's first ever job role?",
choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
answer: 1
}, {
question: "What is Azeem's favourite dish?",
choices: ["Pasta", "Pizza", "Chips", "Curry"],
answer: 0
}, {
question: "What subject did Azeem enjoy the most in school?",
choices: ["Drama", "Science", "P.E", "History"],
answer: 0
}, {
question: "What subject did Azeem least enjoy in school?",
choices: ["Geography", "Maths", "History", "I.T"],
answer: 1
}, {
question: "Which one of these cities has Azeem travelled to?",
choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
answer: 1
}, {
question: "Which college did Azeem study in?",
choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
answer: 3
}, {
question: "Who is Azeem's favourite sports icon?",
choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
answer: 1
}, {
question: "Who is Azeem's favourite music artist?",
choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
answer: 1
}, ];
var currentQuestion = 0;
var questionNumberCounter = 1;
var questionNumber = document.getElementById("questionCount");
var choices = document.getElementById("choicesSection");
var questions = document.getElementById("ques");
questions.innerText = azeem[currentQuestion].question;
// The following event listener will transition from the instructions to the first question of the quiz
document.getElementById("startquiz").addEventListener("click", function() {
$(".quiz-intro").fadeOut(600);
$(".quiz-section").delay(600).slideDown("slow");
questionNumber.innerText = questionNumberCounter;
azeem[currentQuestion].choices.forEach(function(value) {
var radio = document.createElement("input");
var label = document.createElement("label");
var div = document.createElement("div");
$(div).addClass("choice");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "answer");
radio.setAttribute("value", value);
var radioID = 'question-' + currentQuestion;
radio.setAttribute('id', radioID);
label.setAttribute("for", radioID);
label.innerHTML = value + "<br>";
choices.appendChild(div);
div.appendChild(radio);
div.appendChild(label);
})
})
document.getElementById("submitanswer").addEventListener("click", function() {
questionNumberCounter++;
questionNumber.innerText = questionNumberCounter;
currentQuestion++;
if (azeem[currentQuestion]) {
questions.innerText = azeem[currentQuestion].question;
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
} else {
alert("no more questions");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 class="text-center">FAMILY QUIZ</h1>
<h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>
<div class="row text-center quizSection">
<div class="col-md-4 image-section">
<img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
</div>
<div class="col-md-8 quiz-intro">
<h2>INSTRUCTIONS</h2>
<ul id="instructions">
<li>This is a multiple choice quiz</li>
<li>There is only one correct answer per question</li>
<li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>
<li>There are no hints available during the process of the quiz</li>
<li>Click the 'Start Quiz' button to begin</li>
</ul>
<button id="startquiz" class="btn-small btn-success">START QUIZ</button>
</div>
<div class="col-md-8 quiz-section">
<h5>Question <span id="questionCount">1</span> of 15</h5>
<p class="text-center" id="ques"></p>
<div id="choicesSection">
</div>
<input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">
</div>
</div>

How to store JavaScript in a JavaScript array

I'm making a game in JavaScript. The basic idea is to have several buttons that use on.click to perform actions (Fight Monster, Dig for Treasure, etc).
One button loads the next adventure. I have an array containing all the adventures with the values "description" (d), "illustration" (i), and "buttons" (b). The description and illustration HTML show up just fine, but the javascript in the new "Get Flask" button does nothing. Escaping characters doesn't seem to help. Is there a better way to do this?
"Load next adventure" button code: (first couple of lines pick a number randomly up to 5, it has problems that I'll work on next)
<button type="button"
onclick="highLevel = y-1;
while (y >highLevel){ y = Math.round(Math.random() * 5)};
document.getElementById('description').innerHTML = adventure[y].d;
document.getElementById('illustration').innerHTML = adventure[y].i;
document.getElementById('buttons').innerHTML = adventure[y].b"
>Begin</button>
Array code:
adventure[y++]={
d:"Adventure 1",
i:"<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b:"<button type="button" onclick="window.alert('Ye cannot get flask')">Get Flask</button>"
}
For more details, see the code at: https://gist.github.com/janchor/5063f56da41d3e32c825ff154c6bd3be
I didn't change your code much, just fixed what you said :)
function beginClick() {
var highLevel = y - 1;
y = Math.floor(Math.random() * highLevel);
document.getElementById('description').innerHTML = adventure[y].d;
document.getElementById('illustration').innerHTML = adventure[y].i;
document.getElementById('buttons').innerHTML = adventure[y].b
}
var adventure = [];
var y = 0;
adventure[y++] = {
d: "Adventure 1",
i: "<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b: "<button type='button'; onclick='adventure[y].actionGetFlask()'>Get Flask</button>",
actionGetFlask: function() {
alert('Ye cannot get flask');
}
}
<button type="button" onclick="beginClick()">Begin</button>
<div id="description"></div>
<div id="illustration"></div>
<div id="buttons"></div>
Have onclick call a function and move your logic into that.
var adventure = {
d: "Adventure 1",
i: "<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b: "<button type="button" onclick="window.alert('Ye cannot get flask')">Get Flask</button>"
}
function loadHtml() {
document.getElementById('description').innerHTML = adventure.d;
document.getElementById('illustration').innerHTML = adventure.i;
document.getElementById('buttons').innerHTML = adventure.b
}
<button type="button" onclick="loadHtml()">Begin</button>
<div id="description"></div>
<div id="illustration"></div>
<div id="buttons"></div>

Using jQuery to Create True and False Questionnaire [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to figure out the best way to build a questionnaire. See below.
http://cl.ly/image/1W2M3J2z2q2E
http://cl.ly/image/2m461g200b0X
This is what I've got in my code, and it works just fine but as you can see, it gets incredibly long after just two questions. What is the best way to condense this code, so that I do not repeat myself so many times.
// find all anchor tag and prevent default behavior
$('.questions').find('a').on('click', function(e){
e.preventDefault();
});
var ques1 = $('#question1'),
q1 = $('.question1'),
q1True = $('.question1-true').hide(),
q1False = $('.question1-false').hide();
var ques2 = $('#question2'),
q2 = $('.question2').hide(),
q2True = $('.question2-true').hide(),
q2False = $('.question2-false').hide();
(function () {
// click button false
$('#question1 .btn-false').on('click', function(){
q1.hide();
q1True.fadeIn();
});
// click button true
$('#question1 .btn-true').on('click', function(){
q1.hide();
q1False.fadeIn();
});
// click previous button
$('#question1 .prev').on('click', function(){
q1True.hide();
q1False.hide();
q1.show();
});
// click next button
$('#question1 .next').on('click', function(){
ques1.hide();
q2.show();
}); //end question1
// begin question 2
$('#question2 .btn-false').on('click', function(){
ques2.show();
q2.hide();
q2True.show();
});
$('#question2 .btn-true').on('click', function(){
ques2.show();
q2.hide();
q2False.show();
});
})();
Just to give you an idea:
LIVE DEMO
HTML:
<div id="QA">
<div id="qDIV">
<h2></h2>
<button>False</button>
<button>True</button>
</div>
<div id="response">
<p></p>
<button id="prev">Back</button>
<button id="next">Next</button>
<button id="score">Score</button>
</div>
</div>
<pre></pre>
Let's now create an Array of object literals to store data:
var questionnaire = [
{
"question" : "The Earth is round.",
"response" : "The Earth is round!",
"correct" : 1 // 0=False, 1=True
},
{
"question" : "The 'cravat' is originally from France.",
"response" : "The 'cravat' is from Croatia!",
"correct" : 0
},
{
"question" : "Is Java == JavaScript?",
"response" : "It's a different language.",
"correct" : 0
} // Add comma and more objects.
];
This way we can always keep track of the values and inject at every stage an user answer into our current question object.
var $qDIV = $('#qDIV'),
$rDIV = $('#response'),
$qH2 = $("h2", $qDIV),
$answer = $("button", $qDIV),
$response = $("p", $rDIV),
tot = questionnaire.length,
c = 0; // Current Q array counter
function QandA( idx ){
$qDIV.fadeTo(600,1);
$rDIV.hide();
var currQ = questionnaire[c]; // The Object literal from Array
var isCorrect = currQ.correct; // 0 or 1?
var answerIsCorrect = idx==isCorrect; // (compare values) Returns boolean
var resp = answerIsCorrect ? "Great!" : "Wrong!";
currQ.answer = idx; // Put user answer into object (0 or 1)
$qH2.text( (c+1) +'. '+ currQ.question );
$response.text( resp +' '+ currQ.response );
}
QandA();
$answer.click(function(){
var idx = $answer.index(this); // 0 or 1 (get button index)
QandA( idx );
$rDIV.fadeTo(600,1);
$qDIV.hide();
console.log( JSON.stringify(questionnaire, null, 2) ); // TEST ONLY
});
$('#prev, #next').click(function(){
c = this.id=='next' ? ++c : c ; // advance or repeat Question
QandA();
$('#next').toggle(c<tot-1);
$('#score').toggle(c>=tot-1);
});
$('#score').click(function(){
$('pre').text( JSON.stringify(questionnaire, null, 2) ); // TEST
c = 0; // reset questionnary to first question
QandA(); // Restart
});
Previous answer:
LIVE DEMO
having this trivial HTML:
<div id="QA">
<h2></h2>
<span id="buttons"></span>
<p>Points : <span>0</span></p>
</div>
Let's create an array of object literals like:
var questionnaire = [
{
"question" : "The earth is...",
"valid" : 1, // indicates the correct array number, use 0, 1...
"buttons" : ["A cube", "Round"],
"answers" : [ "Ohh, c'mon...", "You got it! It's round!"]
},
{
"question" : "The Cravat is originally from:",
"valid" : 0,
"buttons" : ["Croatia", "France", "Germany"],
"answers" : [ "Great", "Wrong, it's from Croatia!", "Wrong... Sorry"]
},
{
"question" : "Is Java == JavaScript?",
"valid" : 0,
"buttons" : ["False", "True"],
"answers" : ["Exatcly!", "Ohh, c'mon..."]
} // add comma and more Object literals...
];
In the above you can create as many possible buttons and answers you want. jQuery will create the buttons out of the needed object Array. Than you set a valid pointer to tell the questionnaire logic which of the answers index is the correct one using 0, 1, 2....
After jQ creates our buttons, on a button click you can retrieve it's index and target the needed answer out of your object literal, and to determine the points see if the clicked button index matches your valid value.
As you can see you can advance your questions by incrementing a counter variable after every button click (we'll call qc):
var $qa = $('#QA'),
$question = $("h2", $qa),
$buttons = $("#buttons", $qa),
$points = $("p>span",$qa),
questionnaireLength = questionnaire.length, // How many Q?
qc = 0, // Current Question counter
points = 0; // Current points
function QandA(){
var quest = questionnaire[qc],
question = quest.question,
validIdx = quest.valid,
btns = quest.buttons,
answer = quest.answers;
$question.text( question );
if(qc >= questionnaireLength){
return alert("game over");
}
// generate buttons with text:
$buttons.empty();
for(var i=0; i<btns.length; i++){
$buttons.append("<button>"+ btns[i] +"</button>");
}
// Retrieve generated buttons
var $btn = $("button", $buttons);
// Assign click
$btn.one('click', function(){
var idx = $btn.index(this); // get button index
alert("(valid idx is: "+ validIdx +" Clicked button idx: "+ idx +")");
alert("Game says: "+ answer[idx] );
points += (idx === parseInt(validIdx, 10) ? 5 : -5);
$points.text( points );
// Next question
qc++; QandA(); // increment question counter and set new game
});
}
QandA(); // Start game

Adding detailed input forms to quiz results with Javascript

I currently have an online quiz in the making. The current code works fine, but I would like to see who scored what. I am still extremely new to Javascript, and I have been building this quiz for a friend. I have learned quite a bit just getting this thing to work.
Could someone please point me in the right direction on how to add a simple text input or two that will show up when the results page is called at the end of the questions array
I would like to be able to have the user input their name, and submit it along with the results using the php mailer.
I tried to add a simple html input field like below in the HTML area, but it never produced any results.
<input name="Name" type="text" value="" size="80">
Here is my fiddle to see my setup:
var allQuestions = [{
question: "Anger can be thought of as a like other feelings and emotions.",
choices: ["Emotion", "Wave length", "Continuum", "Exercise"],
correctAnswer: 2
}, {
question: "Strong, silent type of personality will usually when things finally overwhelm him.",
choices: ["Explode", "Implode", "Leave", "Cry"],
correctAnswer: 0
}, {
question: "People that complain about everything, and see themselves as victims, fit the personality type called.",
choices: ["Prosecutor", "Grouch", "Exterminator", "Terminator"],
correctAnswer: 1
}, {
question: "When someone wants to point out the faults in others, in order to shift blame off of himself, he is probably a",
choices: ["Displacer", "Intimidator", "Prosecutor", "grouch"],
correctAnswer: 2
},
{
question: "The type of personality takes his anger out on people or things he views as “less threatening” than the person he is actually mad at.",
choices: ["Grouch", "Displacer", "Prosecutor", "Coward"],
correctAnswer: 1
},
{
question: "The easiest type of anger personality to spot is usually the. Often these types come from abusive backgrounds.",
choices: ["Intimidator", "Grouch", "Displacer", "Prosecutor"],
correctAnswer: 0
},
{
question: "Anger has a medical definition, saying it is an state that ranges from to intense fury and rage.",
choices: ["Mental State Embarrassment", "Emotional State Mild Irritation", "Exhausted State Yawning", "Typical State Relaxing"],
correctAnswer: 1
},
{
question: "Anger is often compared to a",
choices: ["Flock of Geese", "Chord of Wood", "Pressure Cooker", "Bag of Ice"],
correctAnswer: 2
},
{
question: "Anger and rage can become a form of . These people are known as rageaholics.",
choices: ["Addiction", "Skin Disease", "Problem", "Comfort Zone"],
correctAnswer: 0
},
{
question: "First rule When you are don’t say anything!",
choices: ["Right", "Wrong", "Angry", "Confused"],
correctAnswer: 2
},
{
question: "Many times, we feel angry because a situation seems negative, and seems to clash with our.",
choices: ["Belief System", "Current Plans", "Family Members", "Schedule"],
correctAnswer: 0
},
{
question: "Many people carry beliefs, that keep them feeling victimized all of the time.",
choices: ["Stoic", "Unusual", "Irrational", "Western"],
correctAnswer: 2
},
{
question: "To contain anger, all we have to do is learn to view life from a perspective.",
choices: ["Personal", "Different", "Closed", "Unknown"],
correctAnswer: 1
},
];
//you can access checkbox name through an array
//match array number to number in allQuestions array
var questionNum = 0;
var scoreNum = 0;
var makeQuestions = "";
var failedQuestions = [];
$(document).ready(function () {
makeQuestions = function () {
if (questionNum === allQuestions.length) {
$("input[value=SUBMIT]").remove();
$("#questions").text(" All Complete!") .append("<br> Please click the button below to submit your results.") .append("<br>Your score is" + " " + scoreNum);
$("#questions").append("<br><input type='button' id='submit_answers' value='SUBMIT'><br><br>");
$("#answers_correct").val(scoreNum);
$("#questions").append("Failed questions: " + failedQuestions.join());
} else {
$("#questions").text(allQuestions[questionNum].question);
for (var i = 0; i < allQuestions[questionNum]['choices'].length; i++) {
$('#words').append('<input type="radio" name="buttons">' + allQuestions[questionNum]['choices'][i] + '</input');
}
}
}
makeQuestions();
$('#submit_answers').on('click', function () {
$('#answer_submission_form').submit();
});
});
var checkQuestions = function () {
var lenG = document.getElementsByName("buttons").length;
console.log(lenG);
var rightAnswer = allQuestions[questionNum]['correctAnswer'];
for (var i = 0; i < lenG; i++) {
if (document.getElementsByName("buttons")[i].checked === true) {
console.log(i);
console.log(document.getElementsByName("buttons")[i].checked);
//compare value to what was inputted
if (i === rightAnswer) {
scoreNum += 1;
alert("Correct! Your score is" + " " + scoreNum);
} else {
failedQuestions.push(questionNum);
alert("False! Your score is still" + " " + scoreNum);
}
}
}
questionNum = questionNum + 1;
$("#words").empty();
makeQuestions();
}
I'm not sure if this is what you need but I have added a fiddle:
http://jsfiddle.net/5Jjam/40/
I have added a div with the id='name'. This contains an input field for entering your text. This will be shown when all the answers have been submitted.

Categories