How to add JS "addEventListener"? - javascript

I have made a little quiz using JS, HTML and CSS. Am using "addEventListener" but it is not working properly and I don't know how to fix it. I have seen other have ask a similar question but none of them solve my problem. I think it should be easy to understand my code. Also if you see any other issues with my code please let me know.
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;
}
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
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 shuffle_questions(questions) {
var currentIndex = questions.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = questions[currentIndex];
questions[currentIndex] = questions[randomIndex];
questions[randomIndex] = temporaryValue;
}
return questions;
}
function restart() {
document.getElementById("quiz").innerHTML = ''; // Clear out the "game over"
questions = shuffle_questions(questions); // Left as an exercise for the reader; see https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
quiz = new Quiz(questions); // Rebuild the quiz object
populate();
return false; // So the link doesn't try to go anywhere
}
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
// message if they would like to try again
gameOverHTML += gameOverHTML.addEventListener("click", restart); //not done yet
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("Which nation won FIFA 2018 World Cup?", ["Peru", "France","Germany", "USA"], "France"),
new Question("Which nation hosted FIFA 2018 World Cup?", ["Sweden", "Russia", "Iran", "South Korea"], "Russia"),
new Question("Which nation has won the most World Cups?", ["Argentina", "Peru","Brazil", "France"], "Brazil"),
new Question("Where was FIFA 2014 World Cup hosted?", ["Ecuador", "Brazil", "France", "All"], "Brazil"),
new Question("Which nation won the first FIFA World Cup", ["Brazil", "Uruguay", "Italy", "Australia"], "Uruguay")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
<!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>FIFA World Cup 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>
<script src="question.js"></script>
</body>
</html>

You should just use event delegation, it's very efficient.
Here a very generic piece of code that will do what you want.
It will work with your generated button, you just have to change classes I target in the event() function.
const event = () => {
document.querySelector('.your-quizz').addEventListener('click', event => {
if (event.target.closest('.your-button')) {
restart();
}
});
};
const restart = () => {
console.log('restart here')
};
event();
<div class="your-quizz">
<button class="your-button">restart</button>
</div>

Related

how to display score on different html page after clicking a button on different page

I'm building a small quiz app, and want to display the user score on a different html page immediately the user finished answering the questions. what am getting right now the user finish answering the questions the in which the score is suppose to display loads and open without the score displayed.
`
<body>
<div class="quiz-title">
<h1>JS Quiz</h1>
</div>
<div class="container">
<h2 id="score-board">00</h2>
<div id="questions"></div>
<div id="answers">
</div>
<button type="submit"class="nbtn">Play</button>
</div>
<script src="quiz.js"></script>
<!-- <script type="text/javascript" src="quiz1.js"></script> -->
</body>
the page to display the score
<body>
<h2 id="score-board">00</h2>
<div>
<button id="play-btn">play</button>
</div>
<script src="quiz.js"></script>
<!-- <script type="text/javascript" src="quiz1.js"></script> -->
</body>
var questionElement = document.getElementById('questions');
var answerElement = document.getElementById('answers');
var scoreBoard = document.querySelector('#score-board');
const state = {
currentQuestionIndex: 0,
score: 0
};
var questions = [
{ question: " 1. javaScript is an....... language?",
answers: [ "object-oriented", "object-based", "procedural", "none of the above"],
correct: 1
},
{ question: " 2.which of the following keywords is used a define variable in javaScript",
answers: [ "var", "let", "both A and B", "none of the above"],
correct: 2
},
{
question: "3. which of the following methods is used to HTML elements using javaScript",
answers: ["getElementsById", "getElementByClassName", "both A and B", "none of the above"] ,
correct: 2
}
];
function showQuestion(questionIndex){
const question = questions[questionIndex];
let qDiv = document.createElement('div');
let p = document.createElement('p');
questionElement.innerHTML = "";
answerElement.innerHTML = "";
p.textContent = question.question;
qDiv.appendChild(p);
questionElement.appendChild(qDiv);
question.answers.forEach((answers, answerIndex) =>{
const $input = document.createElement('input');
const $label = document.createElement('label');
$label.appendChild($input);
$label.appendChild(document.createTextNode(answers));
$input.name = `question${questionIndex}`;
$input.type = 'radio';
$input.value = answerIndex;
answerElement.append($label);
// if ($input.checked === false) {
// console.log('select answer');
// } else{
// showQuestion(state.currentQuestionIndex);
// }
});
};
showQuestion(0);
var nBtn = document.querySelector('.nbtn');
nBtn.addEventListener('click', function(){
state.currentQuestionIndex += 1;
if (state.currentQuestionIndex === questions.length) {
removeLastQuestion();
scorePage();
showScores();
} else{
showQuestion(state.currentQuestionIndex)
}
});
const $answers = document.getElementById("answers");
$answers.addEventListener("change", (event) => {
const currentQuestion = questions[state.currentQuestionIndex];
const selectedAnswerIndex = Number(event.target.value);
const correctAnswerIndex = currentQuestion.correct;
const isCorrect = selectedAnswerIndex === correctAnswerIndex;
state.score += isCorrect ? 1 : 0;
// if (isCorrect) {
// var scoreBoard = document2.querySelector('.score-board');
// // scoreBoard.textContent = state.score;
// // console.log("correct answer");
// } else {
// var scoreBoard = document.querySelector('.score-board');
// // scoreBoard.textContent = state.score += 0;
// // console.log("wrong answer");
// }
});
function showScores() {
if (state.currentQuestionIndex === questions.length) {
scoreBoard.innerHTML = `${state.score}/${questions.length}`
}
}
function removeLastQuestion(){
if (state.currentQuestionIndex > questions.length - 1) {
questionElement.innerHTML = "";
answerElement.innerHTML = "";
}
}
function scorePage() {
if (state.currentQuestionIndex > questions.length -1) {
window.location.href = 'index23.html';
// scoreBoard = document.querySelector('#score-board');
// scoreBoard.innerText = `${state.score}/${questions.length}`;
}
}
// const playBtn = document.querySelector('#play-btn');
// playBtn.addEventListener('click', showQuestion);
`

Add object value to score based on propety name

I am trying to add the value of an object based on the propery name. I have created a quiz and assigned an answer score to each choice (property name). I need to add choices.score to this.score. For example if they select Happy, add 6 to this.score
Everything else is working correctly, I just can't figure out how to add the object value to the score when the choice is selected.
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) {
this.score++ ; //HERE IS WHERE I NEED TO ADD THE SCORE FROM THE SELECTED CHOICE
// I would like it to be this.score + choice.score but cant figure it out
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, choices, score,both) {
this.text = text;
this.choices = Object.keys(choices);
this.score = Object.values(choices);
this.both = Object.entries(choices);
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
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 here
var questions = [
new Question("How are you feeling today?",{'very sad': "1", 'sad':"3",'happy':"6", 'very happy':"9"}),
new Question("How angry are you today?",{'very angry': "1", 'little angry':"3",'not angry':"6", 'very happy':"9"})
];
console.log(questions);
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
<div class="grid">
<div id="quiz">
<h1>Self Assessment</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>
After looking at your code.. i try to find solution.. please refer to below answer:
Instead of converting in key values separate array, u can key in the same array. so that key will be text to show and the value will be the score. when the user will choose to send both and get the answer.
Working sample:
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) {
this.score += Number(answer[1]);
this.questionIndex++;
};
Quiz.prototype.isEnded = function () {
return this.questionIndex === this.questions.length;
};
function Question(text, choices, score, both) {
this.text = text;
this.choices = Object.entries(choices);
this.both = Object.entries(choices);
}
Question.prototype.isCorrectAnswer = function (choice) {
return this.answer === choice;
};
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
const question = quiz.getQuestionIndex(); /// this line
//console.log(question)
var choices = question.choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i][0];
guess("btn" + i, choices[i]); /// this line
}
showProgress();
}
}
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function () {
quiz.guess(guess); /// this line
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("How are you feeling today?", {
"very sad": "1",
sad: "3",
happy: "6",
"very happy": "9",
}),
new Question("How angry are you today?", {
"very angry": "1",
"little angry": "3",
"not angry": "6",
"very happy": "9",
}),
];
// console.log(questions);
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
<div class="grid">
<div id="quiz">
<h1>Self Assessment</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>
ES6:
class Quiz {
constructor(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
getQuestionIndex() {
return this.questions[this.questionIndex];
}
guess(answer) {
this.score += Number(answer[1]);
this.questionIndex++;
}
isEnded() {
return this.questionIndex === this.questions.length;
}
populate() {
if (quiz.isEnded()) {
this.showScores();
} else {
// show question
const element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
const question = quiz.getQuestionIndex(); /// this line
//console.log(question)
const choices = question.choices;
choices.forEach((choice, i) => {
const element = document.getElementById(`choice${i}`);
element.innerHTML = choice[0];
const button = document.getElementById(`btn${i}`);
button.onclick = () => {
this.guess(choice); /// this line
this.populate();
};
});
this.showProgress();
}
}
showProgress() {
const currentQuestionNumber = quiz.questionIndex + 1;
const element = document.getElementById("progress");
element.innerHTML = `Question ${currentQuestionNumber} of ${quiz.questions.length}`;
}
showScores() {
let gameOverHTML = "<h1>Result</h1>";
gameOverHTML += `<h2 id='score'> Your scores: ${quiz.score}</h2>`;
const element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
}
}
class Question {
constructor(text, choices, score, both) {
this.text = text;
this.choices = Object.entries(choices);
this.both = Object.entries(choices);
}
isCorrectAnswer(choice) {
return this.answer === choice;
}
}
// create questions here
const questions = [
new Question("How are you feeling today?", {
"very sad": "1",
sad: "3",
happy: "6",
"very happy": "9",
}),
new Question("How angry are you today?", {
"very angry": "1",
"little angry": "3",
"not angry": "6",
"very happy": "9",
}),
];
// console.log(questions);
// create quiz
const quiz = new Quiz(questions);
// display quiz
quiz.populate();
<div class="grid">
<div id="quiz">
<h1>Self Assessment</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>

How to decrement each click of the animation

I am trying to create animation game. Animation game must consits of One image alternating with another every half a second. I am intended to count++ on each click of the happy-face fish and count-- on each sad-face fish clicked. But, my code is only incrementing, whatever the image is clicked. Also,my code shows me two different images while It must have to be only one.
I have to count a click while my animation is running ( animation: images should be alternating every half a second. It will look like fish is smiling for half second and then crying for another half second then repeats). If i click on happy face, I will score 1 and if click on sad-face I will lose 1. In the end it must show you win if i achieve 10 and resets again on clicking Start Animation.
[Output should be like this:][1]
var image = "happy";
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
fish_img = document.getElementById("happy_fish");
f_img = document.getElementById("happy_fish");
fish_img.classList.add('on');
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
if (image == "happy") {
image = "sad";
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
} else {
image = "happy";
fish_img.src =
"https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="" id="sad_fish" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
I modified your StartAnimation and animationfunction methods to make the fish dissapear with a toggle instead of trying to modify the source of the image.
I made it with a css class off which will make a fish dissapear with display: none;
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
var initialWords = document.getElementById("d");
initialWords.innerHTML = "Your Score: <span id=\"score\">0</span>";
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
var fish_img = document.getElementById("happy_fish");
var f_img = document.getElementById("sad_fish");
fish_img.classList.toggle('off');
f_img.classList.toggle('off');
}
.off {
display: none;
}
<button onClick="StartAnimation()">Start Animation</button>
<br>
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="happy" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="sad" id="sad_fish" class="off" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
You can make things a lot simpler by having one img element and one click handler.
In the snippet I merged the two click handlers into one and added a check for the state of the fish (being represented now by the boolean isHappy).
I attached this handler to a single img element in your HTML and in the animation function I alternate its src attribute between the happy and sad fish according to the isHappy state.
Additionally, Since the counter and the total score are the same, I use only the total score variable.
var isHappy = true;
var totalscore;
var Schedule;
function clickFish() {
if (isHappy) {
totalscore++;
} else {
totalscore--;
}
var scoreSpan = document.getElementById("score");
scoreSpan.innerHTML = totalscore;
if (totalscore === 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + totalscore + " Game Over. You Win!";
}
}
function StartAnimation() {
isHappy = true
totalscore = 0;
clearInterval(Schedule);
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
fish_img = document.getElementById("fish");
isHappy = !isHappy;
if (isHappy) {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
} else {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
}
<button onclick="StartAnimation()">Start animation</button><br />
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="fish" onClick="clickFish()">
<br>
<h1 id="d">
Your Score:
<span id="score">0</span>
</h1>

Javascript flow control glitch

UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.
I'm working on an assembly simulator in Javascript. For some reason the JUMP instruction messes up the register contents. The following program (can be copy-pasted) increments register 'A' (0-->1) then jumps to instruction 0. Instead of '1', the register's content becomes a value over 5000. What am I doing wrong? UPDATE: added three errors caught by the debugger ("Uncaught RangeError: Maximum call stack size exceeded").
var regA = 0;
var regB = 0;
var accu = 0;
var rom = [];
var instCount = 0;
var flag1 = 0;
var stopState = 0;
function eval() {
var inst = document.getElementById("text_f").value;
parseInst(inst);
};
function parseInst(instString) {
if (instString.includes("LDA")) { //ERROR1
var strSplitA = instString.split(":");
regA = parseInt(strSplitA[1]);
document.getElementById("regA").innerHTML = regA;
instCount++;
document.getElementById("demo").innerHTML = "load register A: " + strSplitA[1]+"type of: "+typeof regA;
} else if (instString.includes("LDB")) {
var strSplitB = instString.split(":");
document.getElementById("demo").innerHTML = "load register B: " + strSplitB[1];
regB = parseInt(strSplitB[1]);
document.getElementById("regB").innerHTML = regB;
instCount++;
} else if (instString == "ADD") {
accu = regA + regB;
document.getElementById("demo").innerHTML = "add " + regA + "+" + regB + "=" + accu;
document.getElementById("accu").innerHTML = accu;
instCount++;
} else if (instString.includes("JMP")) {
var jumpTo = instString.split(":");
instCount = parseInt(jumpTo[1]);
document.getElementById("demo").innerHTML = "jump to: " + instCount+" typeof: "+typeof instCount;
document.getElementById("count").innerHTML = instCount;
runStop(stopState,parseInt(jumpTo[1])); //ERROR2
} else if (instString == "CMP") {
if (regA === regB) {
flag1 = 1;
instCount++;
document.getElementById("flag1").innerHTML = 1;
document.getElementById("demo").innerHTML = "flag1 set to 1";
} else {
flag1 = 0;
instCount++;
document.getElementById("flag1").innerHTML = 0;
document.getElementById("demo").innerHTML = "flag1 set to 0";
};
} else if (instString.includes("INC")) {
var incRegister = instString.split(":");
switch (incRegister[1]) {
case "A":
regA++;
document.getElementById("demo").innerHTML = "case A";
document.getElementById("regA").innerHTML = regA;
instCount++;
break;
case "B":
regB++;
document.getElementById("demo").innerHTML = "case B";
document.getElementById("regB").innerHTML = regB;
instCount++;
break;
default:
document.getElementById("demo").innerHTML = "error: register name";
break;
}
} else {
document.getElementById("demo").innerHTML = "error: no instruction";
};
};
function saveToRom() {
var romString = document.getElementById("text_f").value;
rom = romString.split(",");
document.getElementById("rom").innerHTML = rom;
document.getElementById("demo").innerHTML = "#debug:save to rom";
reset();
};
function step() {
parseInst(rom[instCount]);
document.getElementById("count").innerHTML = instCount-1;
};
function run() {
stopState = 0;
document.getElementById("demo").innerHTML = "run";
runStop(stopState,instCount);
};
function stop(){
stopState = 1;
document.getElementById("demo").innerHTML = "stop";
runStop(stopState,instCount);
};
function runStop(stopSt,instructionCount){
if(stopSt == 0){
for(var i=instructionCount;i<rom.length;i++){
parseInst(rom[i]); //ERROR3
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState+" for loop length: " + rom.length;
}
} else {
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState;
};
};
function reset() {
document.getElementById("demo").innerHTML = "debug: reset";
regA = 0;
regB = 0;
accu = 0;
flag1 = 0;
instCount = 0;
document.getElementById("regA").innerHTML = regA;
document.getElementById("regB").innerHTML = regB;
document.getElementById("accu").innerHTML = accu;
document.getElementById("count").innerHTML = instCount;
document.getElementById("flag1").innerHTML = flag1;
};
The full source code with HTML on Github.
I appreciate your help in advance! EDIT: The html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>COMPU</title>
<script type='text/javascript' src='comp3.1.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet_comp.css">
</head>
<body>
<input type="text" id="text_f" value=" " autofocus>
<br><br>
<div class="nav">
<button onclick="eval()">EXEC</button>
<button onclick="saveToRom()">SAVE</button>
<button onclick="reset()">RST</button>
<button onclick="step()">STEP</button>
<button onclick="run()">RUN</button>
<button id="stop" value=0 onclick="stop()">STOP</button>
</div>
<br>
<div class="displays">
DEBUG:
<p id="demo">*debugging messages*</p>
REG A:
<p id="regA">0</p>
REG B:
<p id="regB">0</p>
ACCU:
<p id="accu">0</p>
<br> ROM:
<p id="rom"></p>
INS COUNT:
<p id="count">0</p>
FLAG1:
<p id="flag1">0</p>
<!--
DEBUG2:
<p id="dbg2"></p>
-->
</div>
INSTRUCTIONS:
<ol>
<li>ADD</li>
</ol>
</body>
</html>
UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.

HTML Javascript Self-assessment quiz/questionnaire

Hi so i got a very basic JavaScript HTML quiz working, however what i want to end up with is an assessment type quiz that has lets say 15 questions based on 3 categories (e.g. Alcoholism, depression, drug abuse) e.g.
How often to you drink alcohol?
- All the time
- Occasionally
- Never
the player answers all 15 questions and at the end depending on how they answered the questions they get assigned a category e.g. your category is Drug Abuse etc.
I'm thinking that maybe each category has its own counter and a value is applied to each of the possible answers e.g. All the time gives a score of 3, occasionally scores a 2 etc. As the player answers the questions, the values get stored in the corresponding category and at the end the scores for each category are added up and the category with the highest score gets assigned to the player?
Any help with this would be appreciated :)
HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>
</html>
CSS:
<style>
div#test {
border:#000 1px solid;
padding: 10px 40px 40px 40px;
}
</style>
JS:
<script>
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["How often do you drink?", "All the time", "Often", "Never", "B"],
["Do you ever feel sad for no reason?", "All the time", "Often", "Never", "C"],
["Have you ever tried drugs", "All the time", "Often", "Never", "C"],
["Do you feel uneasy around people", "All the time", "Often", "Never", "C"]
];
function _(x) {
return document.getElementById(x);
}
function renderQuestion () {
test = _("test");
if(pos >= questions.length) {
test.innerHTML = "<h2>Your Category is </h2>";
_("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
_("test_status").innerHTML = "Question "+(pos+1)+" of"+questions.length;
question = questions[pos] [0];
chA = questions[pos] [1];
chB = questions[pos] [2];
chC = questions[pos] [3];
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 onclick='checkAnswer()'>submit Answer</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++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
The executable Javascript snippet its generated by TypeScript(a public GIT repository is available on this bucket), The quiz its organized by arguments and categories; below you can see the UML diagram.
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Categories;
(function (Categories) {
var QuestionCategory = (function () {
function QuestionCategory(value) {
this.Value = value;
}
return QuestionCategory;
})();
Categories.QuestionCategory = QuestionCategory;
var AQuestionCategory = (function (_super) {
__extends(AQuestionCategory, _super);
function AQuestionCategory() {
_super.call(this, 1);
}
return AQuestionCategory;
})(QuestionCategory);
Categories.AQuestionCategory = AQuestionCategory;
var BQuestionCategory = (function (_super) {
__extends(BQuestionCategory, _super);
function BQuestionCategory() {
_super.call(this, 2);
}
return BQuestionCategory;
})(QuestionCategory);
Categories.BQuestionCategory = BQuestionCategory;
var CQuestionCategory = (function (_super) {
__extends(CQuestionCategory, _super);
function CQuestionCategory() {
_super.call(this, 3);
}
return CQuestionCategory;
})(QuestionCategory);
Categories.CQuestionCategory = CQuestionCategory;
})(Categories || (Categories = {}));
var Questions;
(function (Questions) {
var Answer = (function () {
function Answer(text, value) {
this.Text = text;
this.Value = value;
}
return Answer;
})();
Questions.Answer = Answer;
var Question = (function () {
function Question(text, id, category, answers) {
this.Text = text;
this.ID = id;
this.Category = category;
this.Answers = answers;
}
Question.prototype.Render = function () {
var _this = this;
var dContainer = document.createElement("div");
var dQuestion = document.createElement("h3");
dQuestion.innerHTML = this.Text;
dContainer.appendChild(dQuestion);
var dCategory = document.createElement("div");
dCategory.innerHTML = 'Category: ' + this.Category.Value;
dContainer.appendChild(dCategory);
dContainer.appendChild(document.createElement("br"));
var counter = 0;
this.Answers.forEach(function (a) {
var __id = _this.ID + counter;
var dRadio = document.createElement("input");
dRadio.setAttribute('type', 'radio');
dRadio.setAttribute('id', __id);
dRadio.setAttribute('data-category', _this.Category.Value + '');
dRadio.setAttribute('value', a.Value + '');
dRadio.setAttribute('name', _this.ID);
var dLabel = document.createElement("label");
dLabel.innerHTML = a.Text;
dLabel.setAttribute('For', __id);
dContainer.appendChild(dRadio);
dContainer.appendChild(dLabel);
counter++;
});
dContainer.appendChild(document.createElement("hr"));
return dContainer;
};
return Question;
})();
Questions.Question = Question;
var QuestionCollection = (function () {
function QuestionCollection(questions) {
this.Questions = questions;
}
QuestionCollection.prototype.Render = function () {
var div = document.createElement("div");
this.Questions.forEach(function (q) {
div.appendChild(q.Render());
});
return div;
};
return QuestionCollection;
})();
Questions.QuestionCollection = QuestionCollection;
var QuestionArgument = (function () {
function QuestionArgument(name, collection) {
this.Collection = collection;
this.Name = name;
}
QuestionArgument.prototype.Render = function () {
var div = document.createElement("div");
var h1Arg = document.createElement("h1");
h1Arg.innerHTML = this.Name;
div.appendChild(h1Arg);
div.appendChild(document.createElement("hr"));
div.appendChild(this.Collection.Render());
return div;
};
return QuestionArgument;
})();
Questions.QuestionArgument = QuestionArgument;
var QuizManager = (function () {
function QuizManager(hook, arguments) {
this.Arguments = arguments;
this.Hook = hook;
}
QuizManager.prototype.Render = function () {
var _this = this;
this.Arguments.forEach(function (arg) {
_this.Hook.appendChild(arg.Render());
});
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('value', 'Done');
btn.onclick = function (e) {
_this.Compute();
};
this.Hook.appendChild(btn);
};
QuizManager.prototype.Compute = function () {
var _this = this;
var cats = [], dxCat = [], dxCatTotValue = [];
this.Arguments.forEach(function (arg) {
arg.Collection.Questions.forEach(function (q) {
if (cats.length > 0) {
if (cats.indexOf(q.Category) === -1)
cats.push(q.Category);
}
else
cats.push(q.Category);
});
});
cats.forEach(function (c) {
var p = document.querySelectorAll('input[data-category =\'' + c.Value + '\']:checked');
var tv = 0;
for (var i = 0; i < p.length; i++) {
if (parseInt(p[i]['value']) != NaN)
tv += parseInt(p[i]['value']);
}
dxCatTotValue.push({ "Cat": c.Value, "TVal": tv });
});
this.Hook.appendChild(document.createElement("hr"));
var summariH2 = document.createElement("h2");
summariH2.innerHTML = 'Summary';
dxCatTotValue.sort(this.Compare);
dxCatTotValue.forEach(function (catValue) {
var entryDiv = document.createElement("div");
entryDiv.innerHTML = 'Category ' + catValue['Cat'] + ': ' + catValue['TVal'];
_this.Hook.appendChild(entryDiv);
});
this.Hook.appendChild(document.createElement("hr"));
};
QuizManager.prototype.Compare = function (a, b) {
if (a['TVal'] > b['TVal'])
return -1;
if (a['TVal'] < b['TVal'])
return 1;
return 0;
};
return QuizManager;
})();
Questions.QuizManager = QuizManager;
})(Questions || (Questions = {}));
window.onload = function () {
var CCat = new Categories.CQuestionCategory();
var BCat = new Categories.BQuestionCategory();
var ACat = new Categories.AQuestionCategory();
var q1 = new Questions.Question('Do you eat Apples?', 'q1', CCat, [new Questions.Answer('All the time', 1), new Questions.Answer('Occasionally', 2), , new Questions.Answer('Never', 3)]);
var q2 = new Questions.Question('Do you like Pears?', 'q2', BCat, [new Questions.Answer('Yes', 1), new Questions.Answer('No', 2)]);
var fruitsquestions = new Questions.QuestionCollection([q1, q2]);
var fruitsArguments = new Questions.QuestionArgument('Fruits', fruitsquestions);
var q3 = new Questions.Question('Do you eat Onions?', 'q3', ACat, [new Questions.Answer('Yes', 1), new Questions.Answer('No', 2)]);
var q4 = new Questions.Question('Do you like Cucumbers?', 'q4', CCat, [new Questions.Answer('All the time', 1), new Questions.Answer('Occasionally', 2), , new Questions.Answer('Never', 3)]);
var vegetablesQuestions = new Questions.QuestionCollection([q3, q4]);
var vegetablesArguments = new Questions.QuestionArgument('Vegetables', vegetablesQuestions);
var quiz = new Questions.QuizManager(document.getElementById("content"), [fruitsArguments, vegetablesArguments]);
quiz.Render();
};
<div id="content"></div>
The TypeScript source:
module Categories {
export class QuestionCategory {
Value: number;
Text: string;
constructor(value: number) { this.Value = value; }
}
export class AQuestionCategory extends QuestionCategory {
constructor() { super(1); }
}
export class BQuestionCategory extends QuestionCategory {
constructor() { super(2); }
}
export class CQuestionCategory extends QuestionCategory {
constructor() { super(3); }
}
}
module Questions {
import QC = Categories;
export class Answer {
Text: string;
Value: number;
constructor(text: string, value: number) {
this.Text = text;
this.Value = value;
}
}
export class Question {
Category: QC.QuestionCategory;
Answers: Answer[];
Text: string;
ID: string;
constructor(text: string, id: string, category: QC.QuestionCategory, answers: Answer[]) {
this.Text = text;
this.ID = id;
this.Category = category;
this.Answers = answers;
}
Render(): HTMLElement {
var dContainer = document.createElement("div");
var dQuestion = document.createElement("h3")
dQuestion.innerHTML = this.Text;
dContainer.appendChild(dQuestion);
var dCategory = document.createElement("div")
dCategory.innerHTML = 'Category: ' + this.Category.Value;
dContainer.appendChild(dCategory);
dContainer.appendChild(document.createElement("br"));
var counter = 0;
this.Answers.forEach(a => {
var __id = this.ID + counter;
var dRadio = document.createElement("input");
dRadio.setAttribute('type', 'radio');
dRadio.setAttribute('id', __id);
dRadio.setAttribute('data-category', this.Category.Value + '');
dRadio.setAttribute('value', a.Value + '');
dRadio.setAttribute('name', this.ID);
var dLabel = document.createElement("label");
dLabel.innerHTML = a.Text
dLabel.setAttribute('For', __id)
dContainer.appendChild(dRadio);
dContainer.appendChild(dLabel);
counter++;
});
dContainer.appendChild(document.createElement("hr"));
return dContainer;
}
}
export class QuestionCollection {
Questions: Question[];
constructor(questions: Question[]) { this.Questions = questions; }
Render(): HTMLElement {
var div = document.createElement("div");
this.Questions.forEach(q => {
div.appendChild(q.Render());
});
return div;
}
}
export class QuestionArgument {
Name: string;
Collection: QuestionCollection;
constructor(name: string, collection: QuestionCollection) {
this.Collection = collection;
this.Name = name;
}
Render(): HTMLElement {
var div = document.createElement("div");
var h1Arg = document.createElement("h1");
h1Arg.innerHTML = this.Name;
div.appendChild(h1Arg);
div.appendChild(document.createElement("hr"));
div.appendChild(this.Collection.Render());
return div;
}
}
export class QuizManager {
Hook: HTMLElement;
Arguments: QuestionArgument[];
constructor(hook: HTMLElement, arguments: QuestionArgument[]) {
this.Arguments = arguments;
this.Hook = hook;
}
Render() {
this.Arguments.forEach(arg => {
this.Hook.appendChild(arg.Render());
});
var btn = <HTMLButtonElement> document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('value', 'Done');
btn.onclick = (e) => { this.Compute(); }
this.Hook.appendChild(btn);
}
Compute() {
var cats = [], dxCat = [], dxCatTotValue = [];
this.Arguments.forEach(arg => {
arg.Collection.Questions.forEach(q => {
if (cats.length > 0) {
if (cats.indexOf(q.Category) === -1)
cats.push(q.Category);
}
else
cats.push(q.Category);
});
});
cats.forEach(c => {
var p = document.querySelectorAll('input[data-category =\'' + c.Value + '\']:checked');
var tv = 0;
for (var i = 0; i < p.length; i++)
{
if (parseInt(p[i]['value']) != NaN)
tv += parseInt(p[i]['value']);
}
dxCatTotValue.push({ "Cat": c.Value, "TVal": tv });
})
//this.Hook.appendChild(btn);
this.Hook.appendChild(document.createElement("hr"));
var summariH2 = document.createElement("h2");
summariH2.innerHTML = 'Summary';
dxCatTotValue.sort(this.Compare);
dxCatTotValue.forEach(catValue => {
var entryDiv = document.createElement("div");
entryDiv.innerHTML = 'Category ' + catValue['Cat'] + ': ' + catValue['TVal'];
this.Hook.appendChild(entryDiv);
});
this.Hook.appendChild(document.createElement("hr"));
}
Compare(a, b) {
if (a['TVal'] > b['TVal'])
return -1;
if (a['TVal'] < b['TVal'])
return 1;
return 0;
}
}
}
window.onload = () => {
var CCat = new Categories.CQuestionCategory();
var BCat = new Categories.BQuestionCategory();
var ACat = new Categories.AQuestionCategory();
var q1 = new Questions.Question('Do you eat Apples?', 'q1',
CCat,
[new Questions.Answer('All the time', 1), new Questions.Answer('Occasionally', 2), , new Questions.Answer('Never', 3)]);
var q2 = new Questions.Question('Do you like Pears?', 'q2',
BCat,
[new Questions.Answer('Yes', 1), new Questions.Answer('No', 2)]);
var fruitsquestions = new Questions.QuestionCollection([q1, q2]);
var fruitsArguments = new Questions.QuestionArgument('Fruits', fruitsquestions);
var q3 = new Questions.Question('Do you eat Onions?', 'q3',
ACat,
[new Questions.Answer('Yes', 1), new Questions.Answer('No', 2)]);
var q4 = new Questions.Question('Do you like Cucumbers?', 'q4',
CCat,
[new Questions.Answer('All the time', 1), new Questions.Answer('Occasionally', 2), , new Questions.Answer('Never', 3)]);
var vegetablesQuestions = new Questions.QuestionCollection([q3, q4]);
var vegetablesArguments = new Questions.QuestionArgument('Vegetables', vegetablesQuestions);
var quiz = new Questions.QuizManager(document.getElementById("content"), [fruitsArguments, vegetablesArguments]);
quiz.Render();
};
this quiz maker produces a very simple set of HTML and it's obvious where the total calculation is in order to change it.
You can simply add the numbers of questions relating to each answer, then compare to say which is largest and display the result. It gives you a choice of having radio buttons in a list for each question, or several on one line.
All the questions will display on a single page, rather than having to press Next each time which can be annoying for people doing the quiz. No CSS is needed and hardly any javascript.
Example code for a self-scoring quiz with 1 question of each type (drop-down box, short answer, multiple answers etc). The generator tool in the link above will create something similar, it's pure HTML and javascript with no external scripts to load, no jquery or dependencies.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional/EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="../../dkj.css" type="text/css">
<title>Quiz: Sample "Think Again" Quiz</title>
<script type="text/javascript">
<!--
var stuff = new Array (51) // maximum number of questions
var answered = new Array (51) // processing inhibitor for guessers
for(var i = 0; i<=50; i++){stuff[i]=0; answered[i]=0} //initialize arrays// --> </script>
</head>
<body bgcolor ="#ffff88" text="#000000" link="#000088" vlink="purple" alink="#880000" >
<a name="top"></a>
<p align='right'><font size=-1>
Quiz created: 1999/1/31
</font></p>
<center>
<h2><font color="#ff3333">Sample "Think Again" Quiz</font></h2></center>
<noscript>
<p><font color="#880000">
I'm sorry. This page requires that your browser be capable of running JavaScript in order to use the self-correcting feature of the quiz.
In most browsers you can activate JavaScript using a dialog box somewhere under one of the menu bar options. If you are really using a (rare) non-JavaScript-capable browser, you will have to do without the self-grading features of this page.</font></p>
</noscript>
<p>
<b>Instructions: </b>
Answer the multiple choice questions, guessing if necessary,
then click on the "Process Questions" button to see your
score. The program will not reveal which questions you got wrong, only how
many points you have. Go back and change your answers until you get them all
right. (The message box will rejoice at that point and the page will change color in delight.)</p>
<p>
<b>Points to note: </b>
(1) Questions with only one possible answer are one point each.
(2) Questions with <i>one or more</i> possible answers (represented by check boxes)
give a point for each correct answer, but also subtract a point for each wrong answer!
(3) The program will not attempt to score your efforts at all if
you have not tried at least half of the questions.
(4) This practice quiz is for your own use only.
No record of your progress is kept or reported to anyone. </p>
<hr>
<form name="formzSampQuiz">
1. Fog is notorious in
<blockquote>
<input type=radio name=quest1 onClick="stuff[1]=0; answered[1]=1">New York
<input type=radio name=quest1 onClick="stuff[1]=0; answered[1]=1">Chicago
<input type=radio name=quest1 onClick="stuff[1]=1; answered[1]=1">London
<input type=radio name=quest1 onClick="stuff[1]=0; answered[1]=1">Los Angeles
<input type=radio name=quest1 checked onClick="stuff[1]=0; answered[1]=0">No Answer </blockquote>
2. Chicago is in
<blockquote>
<input type=radio name=quest2 onClick="stuff[2]=0; answered[2]=1">Montana
<input type=radio name=quest2 onClick="stuff[2]=0; answered[2]=1">Manitoba
<input type=radio name=quest2 onClick="stuff[2]=0; answered[2]=1">Missouri
<input type=radio name=quest2 onClick="stuff[2]=1; answered[2]=1">Illinois
<input type=radio name=quest2 checked onClick="stuff[2]=0; answered[2]=0">No Answer </blockquote>
3. The famous French Queen Marie Antoinette was married to
<blockquote>
<select name=quest3 size=1 onChange="figureout3()"><option selected>No Answer <option>St. Louis
<option>Louis XVI
<option>Louis DXLVIII
<option>Louis Rukeyser
<option>Louey, brother of Dewey and and Huey
<option>John L. Louis
</select>
<script type="text/javascript"><!-- //Pre-processor for question 3";
function figureout3() {
if (document.formzSampQuiz.quest3.options.selectedIndex == 0)
{stuff[3] = 0; answered[3]=0} // no answer
else if (document.formzSampQuiz.quest3.options.selectedIndex == 2)
{stuff[3] = 1; answered[3]=1} // right answer
else {stuff[3] = 0; answered[3]=1} // wrong answer
} // end function figureout3()
//--></script>
</blockquote>
4. Compared with Elizabeth II, Elizabeth I was
<blockquote>
<input type=radio name=quest4 onClick="stuff[4]=1; answered[4]=1">earlier
<input type=radio name=quest4 onClick="stuff[4]=0; answered[4]=1">later
<input type=radio name=quest4 checked onClick="stuff[4]=0; answered[4]=0">No Answer </blockquote>
5. Which of the Following are saints?
<blockquote>
<script type="text/javascript">
<!-- //Script to pre-process question 5
function figureout5() {
stuff[5]=0; answered[5]=0
if(document.formzSampQuiz.q5p2.checked==true){stuff[5]--; answered[5]=1}
if(document.formzSampQuiz.q5p3.checked==true){stuff[5]++; answered[5]=1}
if(document.formzSampQuiz.q5p4.checked==true){stuff[5]++; answered[5]=1}
if(document.formzSampQuiz.q5p5.checked==true){stuff[5]--; answered[5]=1}
if(document.formzSampQuiz.q5p6.checked==true){stuff[5]--; answered[5]=1}
} //end function figure5
// --></script>
<input type=checkbox name="q5p2" onClick="figureout5()">
Jack-the-Ripper
<input type=checkbox name="q5p3" onClick="figureout5()">
St. Augustine
<input type=checkbox name="q5p4" onClick="figureout5()">
St. Ursula
<input type=checkbox name="q5p5" onClick="figureout5()">
Adolf Hitler
<input type=checkbox name="q5p6" onClick="figureout5()">
Napoleon
</blockquote>
6. Which of the following is <i>not</i> one of the Seven Deadly Sins?
<blockquote>
<select name=quest6 size=1 onChange="figureout6()"><option selected>No Answer <option>pride
<option>lust
<option>envy
<option>stupidity
<option>anger
<option>covetousness
<option>gluttony
<option>sloth
</select>
<script type="text/javascript"><!-- //Pre-processor for question 6";
function figureout6() {
if (document.formzSampQuiz.quest6.options.selectedIndex == 0)
{stuff[6] = 0; answered[6]=0} // no answer
else if (document.formzSampQuiz.quest6.options.selectedIndex == 4)
{stuff[6] = 1; answered[6]=1} // right answer
else {stuff[6] = 0; answered[6]=1} // wrong answer
} // end function figureout6()
//--></script>
</blockquote>
<script type="text/javascript"><!--// Processor for questions 1-6>
function processqzSampQuiz() {
document.bgColor='#ffff88'
var goodguyszSampQuiz=0 // used to calculate score
var inhibitzSampQuiz=0 // used to prevent processing of partially completed forms
for (var i=1; i<=6; i++){
goodguyszSampQuiz=goodguyszSampQuiz + stuff[i]; inhibitzSampQuiz = inhibitzSampQuiz + answered[i];
} // end for
// Prevent display of score if too few questions completed
if (inhibitzSampQuiz < 3){
document.formzSampQuiz.grade.value="You must try at least 3!"
document.formzSampQuiz.score.value= "Secret!";
} // end if
else {
document.formzSampQuiz.score.value=goodguyszSampQuiz;
if (goodguyszSampQuiz==7){
document.formzSampQuiz.grade.value="Hooray!"
document.bgColor="#ff9999"
}else {document.formzSampQuiz.grade.value="Keep Trying!"}
} // end else
} // end function processqzSampQuiz()
function killall(){ //keep final scores from hanging around after reset clears form
goodguys=0; inhibitaa=0;
for (i=0; i<=50; i++){stuff[i]=0; answered[i]=0}
} // end functionl killall()
// --> </script>
<input type=button name=processor value="Process Questions" onClick=processqzSampQuiz()> <input type=reset value="Reset" onClick="killall(); document.bgColor='#ffff88'">
<input type=text name="grade" value="Nothing!" size=25 onFocus="blur()">
Points out of 7:
<input type=text name="score" value="Zip!" size=10 onFocus="blur()">
<br></form>
<p align='right'><font size=-1>
Return to top.</font></p>
<hr>
<!-- You can edit this acknowledgement out if you like. -->
<p align='right'><font size=-1>
This consummately cool, pedagogically compelling, self-correcting, <br>
multiple-choice quiz was produced automatically from <br>
a text file of questions using D.K. Jordan's<br>
<a href="http://anthro.ucsd.edu/~dkjordan/resources/quizzes/quizzes.html">
Think Again Quiz Maker</a> <br>
of October 31, 1998.<br>
</font></p>
</body></html>

Categories

Resources