Trying to create a simple Multiple Choice game - javascript

My function that lists the question and choices won't work. I keep getting the error code document.getElementById(...) is null or not an object. The syntax appears to be correct.
I want the questions and choices to appear in the same divs. I do not want to list all my questions at once. When the user completes a question, they then move on to the next question which will appear in exactly the same divs as the first question until all the questions have been seen.
<script>
var questions = new Array();
questions[0] = 'Is there a difference between a jungle and a rain forest?'
questions[1] = 'What is the world\'s most common religion?',
questions[2] = 'What is the second largest country (in size) in the world?';
var choices = new Array();
choices[0] = ['No difference', 'Some difference', 'Completely different'],
choices[1] = ['Christianity', 'Buddhism', 'Hinduism', 'Islam'],
choices[2] = ['USA', 'China', 'Canada', 'Russia'];
var answers = new Array();
answers[0] = ['Some difference'],
answers[1] = ['Christianity'],
answers[2] = ['Canada'];
var score = 0;
i= 0;
var listQuestion = function(){
if( i < questions.length ){
document.getElementById("myDiv1").innerHTML = '<p>'+questions[i]+'</p>';
for (k=0; k<choices[i].length; k++){
document.getElementById("myDiv2").innerHTML ='<p><input type = "radio" name = "questionchoice">'+choices[i][k]+'</p>';
}
document.getElementById("myDiv3").innerHTML = '<p><button onClick = "getRadioValue()">Check</button></p> <br>';
};
};
var getRadioValue = function(){
for ( var h = 0; h < document.getElementsByName('questionchoice').length; h++ ){
var value = '';
if (document.getElementsByName('questionchoice')[h].checked==true){
value = document.getElementsByName('questionchoice')[h].value;
score+=1
}
}
if (value== answers[i]){
document.getElementById("myDiv4").innerHTML ="That is correct. </br><button input type = 'submit' onClick = 'loadContent()'> Next Question</button>";
}
else {
document.getElementById("myDiv4").innerHTML ="That is incorrect. </br><button input type = 'submit' onClick = 'loadContent()'> Next Question</button>";
}
i++;
};
var whatIsScore = function(){
return score;
}
window.onload = listQuestion();
</script>
</head>
<body>
<div id="myDiv1"></div>
<div id="myDiv2"></div>
<div id="myDiv3"></div>
<div id="myDiv4"></div>
</body>

Here is the full code:
<!DOCTYPE html>
<html>
<head>
<script>
var questions = new Array();
questions[0] = 'Is there a difference between a jungle and a rain forest?';
questions[1] = 'What is the world\'s most common religion?',
questions[2] = 'What is the second largest country (in size) in the world?';
var choices = new Array();
choices[0] = ['No difference', 'Some difference', 'Completely different'],
choices[1] = ['Christianity', 'Buddhism', 'Hinduism', 'Islam'],
choices[2] = ['USA', 'China', 'Canada', 'Russia'];
var answers = new Array();
answers[0] = ['Some difference'],
answers[1] = ['Christianity'],
answers[2] = ['Canada'];
var score = 0;
i= 0;
var listQuestion = function(){
if(i<questions.length){
document.getElementById("myDiv1").innerHTML = '<p>'+questions[i]+'</p>';
var choicesOutput=[];//new Array()
for (var k=0; k<choices[i].length; k++){
choicesOutput.push(
'<p><input type = "radio" name ='
+' "questionchoice">'+choices[i][k]+'</p>');
}
document.getElementById("myDiv2").innerHTML =choicesOutput.join("");
document.getElementById("myDiv3").innerHTML =
'<p><button onClick = "getRadioValue()">Check</button></p> <br>';
}
};
var getRadioValue = function(){
var value = '';
for (var h = 0;
h < document.getElementsByName('questionchoice').length; h++){
if (document.getElementsByName('questionchoice')[h]
.checked==true){
value = document.getElementsByName('questionchoice')[h].value;
score++;
}
}
if (value== answers[i]){
document.getElementById("myDiv4").innerHTML =
"That is correct. </br><button input type = "
+"'submit' onClick = 'loadContent()'> Next Question</button>";
}
else {
document.getElementById("myDiv4").innerHTML ="That is incorrect. "
+"</br><button input type = 'submit' onClick = 'loadContent()'> N"
+"ext Question</button>";
}
i++;
};
var whatIsScore = function(){
return score;
};
function loadContent(){
document.getElementById("myDiv4").innerHTML="";
listQuestion();
}
window.onload = listQuestion;
</script>
</head>
<body>
<div id="myDiv1"></div>
<div id="myDiv2"></div>
<div id="myDiv3"></div>
<div id="myDiv4"></div>
</body>
</html>

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

How to change the colour of the correct answer on a javascript quiz

I am making a javascript quiz: multiple choice with four options. When the answer is correct, I want it turn green before moving onto the next question, if incorrect I want it to turn red and the correct answer to flash green
Edits I have tried make the colour carry over into the next question. Any suggestions?
var currentQuestion =0;
var score = 0;
var totQuestions = questions.length;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
function loadQuestion(questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex +1)+ '.' + q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;};
document.getElementById('opt1').onclick = function loadNextQuestion (){
var selectedOption = document.getElementById('opt1');
var answer = 1;
if(questions[currentQuestion].answer == answer){
score +=1;
}
selectedOption.clicked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totQuestions) {
container.style.display ='none';
resultCont.style.display = '';
resultCont.textContent = 'You scored ' + score;
return;
}
loadQuestion(currentQuestion);
}
Repeated three times four opt2, opt3 and opt 4
This is solved via CSS. You can apply classes to your selected elements as the state requires. I'm not sure which element in your code represents a "correct" answer, but you would get a reference to that and add or remove a class as necessary. Ex:
document.querySelector('.myCorrectAnswerElement').classList.add('greenSuccessClass');
Hope this sample will help you .
HTML:
<div id="item" > I am just a div</div>
<button id="yes">yes</button>
<button id="no">no</button>
CSS :
#item{
width: 500px;
height: 30px;
background-color: red;
}
JS :
var item = document.getElementById("item");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
yes.onclick = function(){
item.style.backgroundColor = "red";
}
no.onclick = function(){
item.style.backgroundColor = "green";
}

appendchild is not working

I am working on nested array. When i am trying to insert data to a div by using appendChild It is throwing an error saying Cannot read property 'appendChild' of null
My Code goes hear
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1 ["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2 ["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3 ["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4 ["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
var Employedisplay = document.getElementById("Employedisplay");
function showEmployes(){
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body>
<input type = "button" id = "MyArray" value ="Show Emps" onclick="showEmployes()"/>
<hr>
<div id="Employedisplay"></div>
</body>
and it is working in this way
function showEmployes(){
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
document.getElementById("Employedisplay").appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
I am not understanding where i am going wrong in my first approach?
The below line of code is executed even before the browser add the #Employedisplay element in DOM.
var Employedisplay = document.getElementById("Employedisplay");
So when you click the button, Employedisplay variable is null
It's better to bootstrap your code on page load, or you can get the #Employedisplay element at the start of showEmployee method.
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
function bootstrap() {
var Employedisplay = document.getElementById("Employedisplay");
}
function showEmployes() {
var n = emps.length;
for (i = 0; i < n; i++) {
var emp = emps[i];
for (var key in emp) {
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body onload="bootstrap();">
<input type="button" id="MyArray" value="Show Emps" onclick="showEmployes()" />
<hr>
<div id="Employedisplay"></div>
</body>
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1 ["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2 ["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3 ["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4 ["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
function showEmployes(){
var Employedisplay = document.getElementById("Employedisplay");
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body>
<input type = "button" id = "MyArray" value ="Show Emps" onclick="showEmployes()"/>
<hr>
<div id="Employedisplay"></div>
</body>

using Javascript how to display element one by one on click

how to display element one by one on click using only Javascript, in my example when I click all elements show at once, but i need only one click - one element. I appreciate if you show the simplest way to do if in order to i can understand how it works
$(function() {
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i;
for (i = 0; i <cars.length; i++) {
x += cars[i] + "<br>";
}
document.getElementById("btn").onclick = function() {
document.getElementById("text").innerHTML = x;
}
});
You may update your code as follows. At the very beginnig, your are initializing x with empty string. Then for each click on button, append an element from array with new line tag.
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i = 0;
document.getElementById("btn").onclick = function() {
if( i < cars.length) {
x += cars[i++] + "<br>";
}
document.getElementById("text").innerHTML = x;
}
<p id="text"></p>
<button id="btn">Result</button>
<html>
<script>
var cars = ["audi", "bmw", "volvo"];
var x = "";
var count = 0;
function appendArray(){
if(count<cars.length){
x += cars[count]+ "<br>";
document.getElementById("appendText").innerHTML = x;
count++;
}else{
count = 0;
document.getElementById("appendText").innerHTML = "";
}
}
</script>
<p id="appendText"></p>
<button onclick="appendArray()">Submit</button>
</html>
Here is one solution in vanilla javascript:
var button = document.getElementsByTagName('button')[0];
var i = 0;
function addCar(i) {
var cars = ['audi', 'bmw', 'volvo'];
var paragraph = document.getElementsByTagName('p')[0];
if (i < cars.length) {
var newLine = document.createElement('br');
var newCar = document.createTextNode(cars[i]);
paragraph.appendChild(newLine);
paragraph.appendChild(newCar);
}
}
button.addEventListener('click',function(){addCar(i); i++;},false);
<p></p>
<button>Click for a New Car</button>

Java Script drop down options controlled by another drop down

I am extremely new to JavaScript. I am trying to control the options inside one listbox (called Aggregator) using the selected value of another (called Product). Below is the code I have written so far.
Now when I load the HTML page the code I have written to control the text boxes (using txt, txt2, txt3) does not work either now.
Javascript
function pGo() {
var x = document.getElementById("Product").value;
var txt = "";
var txt2 = "";
var txt3 = "";
var list = document.getElementById("Aggregator");
var aggrs = new Array();
aggrs[0] = "h";
aggrs[1] = "e";
aggrs[2] = "l";
aggrs[3] = "l";
aggrs[4] = "l";
aggrs[5] = "o";
aggrs[6] = "o";
var length = aggrs.length;
var element = null;
if (x == "HII") {
txt = "Full ";
txt2 = "/";
txt3 = "/";
for (var i = 0; i < 5; i++)){
element = aggrs[i]
var opt = document.createElement("option");
opt.innerText = element;
opt.setAttribute(element, 'newvalue');
list.appendChild(opt);
}
}
else if (x == "DLG"){
txt = "Full";
txt2 = "/T";
txt3 = "/responses/";
for (var i = 0; i < 1; i++)){
element = aggrs[i]
var opt = document.createElement("option");
opt.innerText = element;
opt.setAttribute(element, 'newvalue');
list.appendChild(opt);
}
}
else if (x == "TBB"){
txt = "Full ";
txt2 = "/Trams";
txt3 = "/respo";
for (var i = 0; i < 1; i++)){
element = aggrs[i]
var opt = document.createElement("option");
opt.innerText = element;
opt.setAttribute(element, 'newvalue');
list.appendChild(opt);
}
element = aggrs[6]
var opt = document.createElement("option");
opt.innerText = element;
opt.setAttribute(element, 'newvalue');
list.appendChild(opt);
}
form.elements.calcType.value = txt;
form.elements.transform.value = txt2;
form.elements.calcResponse.value = txt3;
}
HTML
product
<select id="Product" onchange = "pGo()">
<option>HII</option>
<option>DLG</option>
<option>TBB</option>
</select><div>
<script type = "text/javascript">
aggregator
<select name = "Aggregator">
</select><br/><br/>
Other text boxes emitted
I need the Aggregator to display certain values from the aggrs list depending on the value selected in the Product select:
HII : [0,1,2,3,4,5]
DLG : [0,1]
TBB : [0,1,6]
Don't go learning jQuery if you're having trouble with basic JavaScript. You'll have worse problems with jQuery.
For a start, you're asking for the ID "Aggregator":
var list = document.getElementById("Aggregator");
when you don't have an object with the ID "Aggregator":
<select name = "Aggregator"></select>
First off, there are a LOT of syntax errors in your code. I have added comments where I made those changes.
There was no id element "Aggregator" so I changed your markup:
product
<select id="Product" onchange="pGo();">
<option>Pick one</option>
<option>HII</option>
<option>DLG</option>
<option>TBB</option>
</select>
<div>aggregator
<select id="Aggregator" name="Aggregator"></select>
<br/>
<br/>
</div>
You had a lot of duplicate code (still is some) and other issues (see comments)
// function to remove duplicate code
function addOptions(list, aggrs, limit) {
var i = 0;
// fix issue where option list did not empty on new select
for (; i < list.length; i++) {
list.remove(i);
}
for (i = 0; i < limit; i++) { // fix extra ")"
var opt = document.createElement("option");
element = aggrs[i]; //missing semicolon
opt.text = element; // use standard form not innerHtml
opt.value = element; // you had no value
opt.setAttribute(element, 'newvalue');
list.appendChild(opt);
}
}
function pGo() {
var x = document.getElementById("Product").value;
var txt = "";
var txt2 = "";
var txt3 = "";
var list = document.getElementById("Aggregator");
var aggrs = ["h", "e", "l", "l", "l", "o", "o"]; //simpler array
var length = aggrs.length;
var element = null;
if (x == "HII") {
txt = "Full ";
txt2 = "/";
txt3 = "/";
addOptions(list, aggrs, 5);
} else if (x == "DLG") {
txt = "Full";
txt2 = "/T";
txt3 = "/responses/";
addOptions(list, aggrs, 1);
} else if (x == "TBB") {
txt = "Full ";
txt2 = "/Trams";
txt3 = "/respo";
addOptions(list, aggrs, 1);
// strange additional option added
var oneAggr = [];
oneAggr[0] = aggrs[6];
addOptions(list, oneAggr, 1);
}
// form.elements.calcType.value = txt; // commented out due to not existing
// form.elements.transform.value = txt2;
// form.elements.calcResponse.value = txt3;
}
This is NOT really pretty (OK it is somewhat strange the options you set) even yet but at least it should work.
Sample to work with: http://jsfiddle.net/Qc4yD/

Categories

Resources