Repopulating objects with a click - javascript

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>

Related

How to give h1div+1 after give correct answer?

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/

My generated french word duplicates? When it shouldn't be

I've sorted this but now it's came back on... I've tried changing the for loops but it still seems to generate duplicate French words. It's suppose to not show the french word twice in the application run.
My jsFiddle is an exact replica:
http://jsfiddle.net/jamesw1/w8p7b6p3/17/
Javascript:
//James Wainwright's Mobile Apps Assignment
//Arrays of french and english words.
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers and make sure they aren't the same as each other.
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu using for loop. This loop runs once (on document load)
document.getElementById('generatedWord').textContent = foreignWords[number];
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Output the previous.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Declare variables 'outside' the onclick function so it ensures they work correctly.
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
var counter = 0;
var outputted = '';
//Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
var guessedList = new Array(6);
var correctList = new Array(6);
var wordGenerated = new Array(6);
//On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
document.getElementById('submitAns').onclick = function () {
//Declare variables for function.
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
//Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Generate a word here. ( call wordGen() )
wordGen();
//Create dynamic select menu for options they have to choose from.
document.getElementById('generatedWord').textContent = foreignWords[number];
//Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Outputting to the html page.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
//Count number of guesses
numGuesses++;
//Counter for placing guessed, correct and foreign word into there arrays.
counter++;
wordGenerated[counter] = foreignWords[number];
guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
correctList[counter] = translate[number];
//Once the application has finished...It will produce the following output.
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
outputted = "<table>";
for(var d=1;d<wordGenerated.length;d++){
outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td> <td>Guessed Word: " + guessedList[d] + "</td> <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
}
outputted += "</table>";
outputted += "<style type='text/css'>#hint{ display:none; }</style>";
//Output it to the html page.
document.getElementById('details').innerHTML = outputted;
}
};
document.getElementById('hint').onclick = function () {
alert(correctAns.charAt(0));
};
Html:
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="header">
<h1>James' Translation Guessing Game</h1>
</div>
<div data-role="content" class="main">
<h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />
<!-- What question we're upto -->
<h2 id="numGuess">Question #</h2 >
<!-- The generated French Word Aswell as end of app details-->
<div align="center" class="frenchWord" style="position:">
<!--Generated french word details-->
<div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center" id="generatedWord"></div>
<br />
<br />
<!-- Show the user there guessed answers, correct and foreign word -->
<div id="details"></div>
</div>
<!-- Select menu output -->
<div align="center" id="output"></div>
<img id="hintImg" style="" src="images/hint.png" alt="Hint" />
<!-- Buttons, Call Functions -->
<button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
<input type="button" value="New Game" onClick="document.location.reload(true)">
<script>
//Simple animation
$(document).ready(function(){
$("#generatedWord").animate({
opacity: 0.8,
margin: "40px 0px 100px 0px",
width: "20%",
padding: "30px",
}, 1500 );
});
</script>
</div>
<div data-role="footer">
<h4>James Wainwright</h4>
</div>
</div>
This might do it. Before assigning a number to the RanNumbers array I delete it from the original RanNumbers array to prevent duplication. It might make more sense to just maintain a separate array of numbers to be used in the questions but I tried to change as little as possible.
Updated Fiddle
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * RanNumbers.length);
while(temp==correctAns){
temp = Math.floor(Math.random() * RanNumbers.length);
delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}

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)

HTML5 Javascript, Updating a text using arrays

Dont mind my code, it is probably very terrible in the eyes of professionals aha but anyway
i am coding a game where the user has to answer a question with 3 options, the question, the 3 answers are all set in arrays [1] to [10]. My problem is that when the question is asked, the question wont update on the website.
<head>
<script type="text/javascript">
var Question = new Array(10);
var Answer1 = new Array(10);
var Answer2 = new Array(10);
var Answer3 = new Array(10);
var i = 1;
(example of one question)
Question[1] = "What time is it?";
Answer1[1] = "1.I dont know";
Answer2[1] = "2.Party Time";
Answer3[1] = "3.None of your business";
</script>
(my function that writes the questions/answers)
<script type="text/javascript">
function displayQuestions() {
document.write(Question[i].toString());
document.write("\n <br>" + Answer1[i].toString());
document.write("\n <br>" + Answer2[i].toString());
document.write("\n <br>" + Answer3[i].toString());
}
</script>
</head>
<body>
<div>My Question Game!</div>
<div id="Question"><script type="text/javascript">displayQuestions();</script></div>
<button onclick="answerGet()">Answer</button>
<script type="text/javascript">
function answerGet()
{
var answer = 0;
answer = parseInt(prompt("Please enter your answer (1 - 3) "));
if (answer < 4 && answer > 0) {
} else if (isNaN(answer)) {
parseInt(prompt("It is not a number. Please enter a number from 1 to 3", ""));
} else {
parseInt(prompt("Your number (" + answer + ") is above 3. Please enter a number from 1 to 3"));
if ((answer() === CorrectAnswer[i])) {
score = score + 50;
}
i = i + 1;
alert(i);
Question = Question[i];
Answer1 = Answer1[i];
Answer2 = Answer2[i];
Answer3 = Answer3[i];
CorrectAnswer = Correctanswer[i];
}
To make your program a bit more slick, you should use jquery.
Sans that to fix your immediate problem, try calling your displayQuestions function after the correct answer is given, like the following:
Answer1 = Answer1[i];
Answer2 = Answer2[i];
Answer3 = Answer3[i];
CorrectAnswer = Correctanswer[i];
displayQuestions();
Your code isn't that bad. Here is how you can update the questions:
In your answerGet() function, add the following to the if ((answer() === CorrectAnswer[i])) block
var question = document.getElementById('question');
question.innerHTML = displayQuestions();
This will get the text from displayQuestions() and put it inside the question div. But there is still a problem, the displayQuestions() function actually prints to the screen. We want it to return text instead, like this:
function displayQuestions() {
var text = Question[i].toString();
text += "\n <br>" + Answer1[i].toString())
text += "\n <br>" + Answer2[i].toString();
text += "\n <br>" + Answer3[i].toString();
return text;
}
Now one final problem: the code that prints the first question is now wrong because the displayQuestions() function doesn't print anything, just returns the text. Lets fix that:
<div id="Question"><script type="text/javascript">document.write(displayQuestions());</script><div>
That should do it. Let me know if you have any trouble implementing that.

Making a quiz app, stuck on a function

I'm making a simple quiz app. But I'm stuck on ordering the functions.
Here is the code
// questions set
var qtnsSet = [
// format: [question, [comma, separated, options], index of correct ans. eg. 1]
["What is the full form of IP?", ["Internet Provider", "Internet Port", "Internet Protocol"], 2],
["Who is the founder of Microsoft?", ["Bill Gates", "Steve Jobs", "Steve Wozniak"], 0],
["Full name of IBM?", ["Internet Business Machine", "International Business Machine", "Indian Business Machine"], 1]
]
// init vars
var qtnNo = 0,
score = 0;
// define elements
var qtnContainer = $("qtn-container"),
optnsContainer = $("optns-container"),
submitBtn = $("submit-btn");
function $(id) { // Shortcut for document.getElementById
return document.getElementById(id);
}
function askQtn() { // ask question
var optns = qtnsSet[qtnNo][1], // options array
optnsHtml = "";
for (var optnNo = 0; optnNo < optns.length; optnNo++) {
optnsHtml += createOptnHtml(optnNo, optns[optnNo]);
}
qtnContainer.textContent = qtnsSet[qtnNo][0]; // question
optnsContainer.innerHTML = optnsHtml; // options
}
function createOptnHtml(optnNo, optn) { // create html elements for options
// eg. <li><input type='radio' name='optn' value='Option' id='optn-0'>
// <label for='optn-0'>Option</label></li>
return "<li><h3><input type='radio' name='optn' value='" + optn + "' id='optn-" + optnNo + "'>" +
" <label for='optn-" + optnNo + "'>" + optn + "</label></h3></li>";
}
function getGivenAns() { // get the answer given by user
var optns = document.getElementsByName("optn");
for (var optnNo = 0; optnNo < optns.length; optnNo++) {
if (optns[optnNo].checked) {
return optnNo; // index of the chosen answer
}
}
}
function checkAns() { // check if user's right or not
if (getGivenAns() == qtnsSet[qtnNo][2]) {
score += 6; // 6 points for right answer
}
}
function submitAns() {
if (qtnNo <= qtnsSet.length) {
if (getGivenAns()) {
checkAns();
qtnNo++;
askQtn();
} else {
alert("Please choose an answer.");
};
} else {
alert("Score: " + score);
};
}
window.addEventListener("load", askQtn, false);
submitBtn.addEventListener("click", submitAns, false);
I'm unable to configure the submitAns() function so that every thing works correctly.
How can I order the functions inside submitAns()?
getGivenAns()
Returns the index of the options, which can be 0 if the first option is selected which would evaluate to false here:
if (getGivenAns()) {
so just return true if an option is checked.
Also
if (qtnNo <= qtnsSet.length) {
Will be true after the last question it should just be
if (qtnNo < qtnsSet.length) {

Categories

Resources