I've created a quiz which takes answer from user, checks it and shows whether the answer is correct or incorrect. There are 8 questions in it. I want to start the quiz again once all these 8 questions are completed. How do I do it ?
This is my code
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<div class="qscore">
<span id="scr"></span>
</div>
<center>
<div class="qstart">start</div>
</center>
<div class="qarea">
<div class="question">father</div>
<div class="canswer">Vater</div>
<textarea class="abox" placeholder="Translate the text to German"></textarea>
</div>
<div class="qarea">
<div class="question">My father is baba</div>
<div class="canswer">Mein Vater ist baba</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Land</div>
<div class="canswer">Land</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">My Mother</div>
<div class="canswer">Meine Mutter</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Brother</div>
<div class="canswer">Bruder</div>
<textarea class="abox" placeholder="Translate the text to German"></textarea>
</div>
<div class="qarea">
<div class="question">City</div>
<div class="canswer">Stadt</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Woman</div>
<div class="canswer">Frau</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Man</div>
<div class="canswer">Mann</div>
<textarea class="abox"></textarea>
</div>
<div class="qsubmit">submit</div>
<div class="qcontinue">continue</div>
<div class="correct">Correct</div>
<div class="incorrect">Incorrect</div>
<div class="qrating"></div>
<div class="startagain">startagain</div>
Jquery
$(document).ready(function () {
//declare variables
var qarea = $(".qarea");
var totalqarea = qarea.length;
var startagain = $(".startagain");
var canswer = $(".canswer")
var qsubmit = $(".qsubmit");
var qcontinue = $(".qcontinue");
var qscore = $(".qscore");
var counter = 0;
//hide unrequired
qcontinue.hide();
qsubmit.hide();
startagain.hide();
$("startagain")
$(".correct,.incorrect").hide();
qsubmit.hide();
$(".qscore,.qrating").hide();
$(".canswer").hide();
qarea.hide();
var qstart = $(".qstart");
//intiate click on start
qstart.click(function () {
$(".correct,.incorrect").hide();
var counter = 0;
$(".abox").val('');
qsubmit.show();
$(".qrating").hide();
qarea.eq(counter).show();
qstart.hide();
var i = 0;
$(".qscore").text("Score:" + i + "/" + totalqarea).show();
//loop(); function loop()
//initate submit
qsubmit.bind("click", function () {
qstart.hide();
var ma = canswer.eq(counter).text();
var mal = ma.replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace("ü", "u").replace("ä", "ä").replace("ö", "o").replace("ß", "ss").replace("Ä", "A").replace("Ö", "O").replace("Ü", "U").toLowerCase();
var masplt = mal.split(" ");
var ua = $("textarea").eq(counter).val();
var ual = ua.replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace("ü", "u").replace("ä", "a").replace("ö", "o").replace("ß", "ss").replace("Ä", "A").replace("Ö", "O").replace("Ü", "U").toLowerCase();
var uasplt = ual.split(" ");
var n = mal.localeCompare(ual);
counter = counter + 1;
qarea.eq(counter - 1).hide();
// checks correct answer and gives score
if (n == 0) {
var praise = ["Well Done !!..You got it right !! ", "Nice....You got it right!! ", "Perfect....You got it right!! "]
var r = Math.round(Math.random());
$(".correct").text(praise[r] + " : The answer is " + ma).show();
i = i + 1;
$(".qscore").text("Score:" + i + "/" + totalqarea).show();
//gives incorrect
} else {
qarea.hide();
$(".incorrect").text("Oops....the correct answer is....");
for (var j = 0; j < masplt.length; j++) {
if (masplt[j] !== uasplt[j]) {
$(".incorrect").append(" <span style='font-size:32px'>" + masplt[j] + "</span>").show();
} else {
$(".incorrect").append(" " + masplt[j]).show();
}
}
//$(".incorrect").text("Oops....the correct answer is " + ma).show();
}
qsubmit.hide();
qcontinue.show();
qcontinue.click(function () {
qarea.eq(counter).show();
$(".correct,.incorrect").hide();
qsubmit.show();
qcontinue.hide();
})
if (totalqarea == counter) {
qcontinue.show();
qcontinue.click(function () {
qsubmit.hide();
qstart.text("start again").show();
if (i < (totalqarea - 6) && i < (totalqarea - 4)) {
$(".qrating").text("Your scored " + i + "/" + totalqarea + ". ...You need some more practice. Try it again.").show();
} else if (i > (totalqarea - 4) && i < (totalqarea - 2)) {
$(".qrating").text("Your scored " + i + "/" + totalqarea + "....Not bad !!").show();
} else {
$(".qrating").html("Your scored " + i + "/" + totalqarea + "....Wünderbar !! Keep it up !!").show();
}
$("#scr").text('');
})
qstart.click(function () {
})
}
})
})
})
Here is the fiddle
http://jsfiddle.net/qFa39/11/
Thanks.
Currently you're declaring 2 different counter variables. The one declared under the "declare variables" comment and the one declared within qstart.click(). To fix your problem replace the line inside qstart.click() (line 31 in the jsfiddle) with:
counter = 0;
No var preceeding it. This way javascript will understand you are refering to the first counter and not creating a new var called counter. Have a read up on scope in javascript for more info.
Although this does reveal another bug with our code where the 'Start Again' button does then not hide properly.
Related
The code works when the day1.js script is loaded in the index and if a certain snippet from the HTML template is pasted into the file, but it doesn't work when I switch to the page using ng-view with the same code. There is nothing in my day1controller. I'm pretty lost at this point and would appreciate some insight.
I keep getting the error
day1.js:5 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
Here is my index:
<!-- Takes in an input.txt and counts how many times the numbers increase and decrease -->
<!DOCTYPE html>
<html ng-app="adventOfCode">
<head>
<title>Home</title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular-route.min.js"></script>
<meta name="vieport" content="width=device-width initial scale=1" />
</head>
<body>
<header><h2>Website Header</h2></header>
<div class="column">
<div class="links">
Home<br />
Day 1<br />
Day 2<br />
</div>
</div>
<!-- Where the pages change -->
<div ng-view></div>
<!-- Code only works as intended when this div is pasted here -->
<div>
<input type="file" />
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<!-- End of pasted code -->
<footer><h3>Website footer lalalala</h3></footer>
<script>
var app = angular
.module("adventOfCode", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
//inject $locationProvider service
$locationProvider.hashPrefix(""); // add configuration
$routeProvider
.when("/home", {
template: "About Us",
})
.when("/day1", {
templateUrl: "views/day1.html",
controller: "day1Controller",
})
.when("/day2", {
templateUrl: "views/day2.html",
controller: "day2Controller",
});
});
</script>
<!-- Controllers -->
<script src="js/controllers/day1Controller.js"></script>
<script src="js/controllers/day2Controller.js"></script>
<!-- My scripts -->
<script src="js/day1.js"></script>
</body>
</html>
`
Here is the javascript I am trying to run (day1.js):
//selecting the input and textarea elements and saving them to variables
let input = document.querySelector("input");
let textarea = document.querySelector("textarea");
input.addEventListener("change", () => {
//returns an array of File objects
let files = input.files;
if (files.length == 0) return;
//getting the first File object
const file = files[0];
//creating a FileReader
let reader = new FileReader();
reader.onload = (e) => {
var index = 0;
var lastLine = "";
var currentLine = "";
var increased = 0;
var decreased = 0;
var results = [];
const file = e.target.result;
console.log("inside onload");
/**We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable. */
const lines = file.split(/\r\n|\n/);
console.log("split the lines");
/**-------------- Our Workspace -------------- */
lines.forEach((line) => {
if (index === 0) {
lastLine = line;
console.log(line + "-->" + index);
index++;
} else {
currentLine = line;
if (currentLine > lastLine) {
console.log(line + " --> " + index + " :increased");
increased++;
} else if (currentLine < lastLine) {
console.log(line + " --> " + index + " :decreased");
decreased++;
} else {
console.log(line + " --> " + index);
}
index++;
lastLine = currentLine;
}
});
console.log("Number of inputs: " + index);
console.log("How many times the inputs increased: " + increased); //1582 is too low
console.log("How many times the inputs decreased: " + decreased);
document.getElementById("increase").innerHTML =
"How many times the inputs increased: " + increased;
document.getElementById("decrease").innerHTML =
"How many times the inputs decreased: " + decreased;
results = slidingWindow(lines, 3);
document.getElementById("increase_").innerHTML =
"How many times the inputs increased: " + results[0];
document.getElementById("decrease_").innerHTML =
"How many times the inputs decreased: " + results[1];
document.getElementById("Index").innerHTML = "Number of inputs: " + index;
/**We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element. */
textarea.value = lines.join("\n");
console.log("joined the lines");
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
function slidingWindow(linesArray, windowSize) {
if (windowSize < 0 || windowSize > linesArray.length) return null;
let currentSum = 0;
let lastSum = 0;
let increased = 0;
let decreased = 0;
let results = [];
for (let i = 0; i < linesArray.length; i++) {
currentSum += parseInt(linesArray[i]);
if (i >= windowSize - 1) {
if ((lastSum === 0) && (currentSum > lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
} else if (currentSum > lastSum) {
console.log(currentSum + " --> " + i + " :increased");
increased++;
} else if (currentSum < lastSum) {
console.log(currentSum + " --> " + i + " :decreased");
decreased++;
} else if ((currentSum = lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
}
lastSum = currentSum;
currentSum -= linesArray[i - (windowSize - 1)];
}
}
return (results = [increased, decreased]);
}
Here is day1.html, which is what I'm want to use to run day1.js:
<div>
<input type="file">
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<div>
<h3>Increase or Decrease</h3>
<h2 id="increase"></h2>
<h2 id="decrease"></h2>
<h3>Sliding window</h3>
<h2 id="increase_"></h2>
<h2 id="decrease_"></h2>
<h3 id="Index"></h3>
</div>
You have to use container for place your view.ng- view is a directive that works like a placeholder. It creates a placeholder where a corresponding view can be placed based on the configuration.
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="nav">
Home
About
</div>
</div>
</div>
</div>
<div class="container">
<div ng-view=""></div>
</div>
My problem was that I didn't have the Jquery library in my index.html. Without it the scripts aren't executed when loaded by ng-view.
I'm not sure how to add a new building by array. I'm a beginner javascript person.
I added saving/loading among other things to the back end but the client side is giving me issues for some reason.
I think it has something to do with me not under standing arrays correctly but if you could point me in the right direction i would love to learn.
I want to add a second building called
loadbuilding("taco stand")
Here is the code:
var Timer = window.setInterval(function() {
Tick()
}, 1000);
var buildings = [];
//The object declaration for game saves
function GameSave() {
this.money = 0;
this.buildings = [];
for (var i = 0; i < buildings.length; i++) {
this.buildings[i] = 0;
}
}
//The object declaration for buildings
function Building() {
this.Name = "Lemonade Stand";
this.Cost = 10;
this.PerSec = 1;
}
//The function to initialise all buildings
function InitBuildings() {
LoadBuilding("Lemonade Stand", 10, 1);
LoadBuilding("Taco Stand", 100, 1);
}
//The function to automatically load a building into the buildings array
function LoadBuilding(name, cost, persec) {
var cur = buildings.length;
buildings[cur] = new Building();
buildings[cur].Name = name;
buildings[cur].Cost = cost;
buildings[cur].PerSec = persec;
}
//The function used to gather money
function GatherMoney() {
game.money++; //++ tells javascript to add 1 to the variable
//Display the player's current money
document.getElementById("money").innerHTML = game.money;
}
//The function that gets run every second
function Tick() {
for (var i = 0; i < buildings.length; i++) {
game.money += game.buildings[i] * buildings[i].PerSec;
}
document.getElementById("money").innerHTML = game.money;
}
//The function to buy a lemonade stand
function Build(id) {
if (game.money >= buildings[id].Cost) { //Check if the player has enough money, then subtract it and add a new building if they do
game.money -= buildings[id].Cost;
game.buildings[id] = game.buildings[id] + 1;
document.getElementById("money").innerHTML = game.money;
document.getElementById("Building1Qty").innerHTML = game.buildings[id];
}
}
//Run this code once the page has loaded fully
window.onload = function() {
InitBuildings();
window.game = new GameSave();
};
<!--Pleae refer to Lesson 9.txt for a full description on this lesson -->
<html>
<head>
<title>Basic Incremental Game</title>
<link rel="stylesheet" type="text/css" href="css/Incremental.css">
<script src="js/Incremental.js"></script>
</head>
<body>
<div id="page">
<div id="header">
<div id="game-title">
Basic Incremental Game
</div>
</div>
<div id="content">
<div id="stats" class="block">
<div class="label">Money:</div>
<div id="money" class="label">0</div>
</div>
<div id="clickables" class="block">
<input type="button" value="Click Me!" onclick="GatherMoney();">
</div>
<div id="buildings" class="block">
<div id="Building1">
<input type="button" value="Lemonade Stand" onclick="Build(0);">
<div>
<div class="label">Cost:</div>
<div id="Building1Cost" class="label">10</div>
</div>
<div>
<div class="label">Per Sec:</div>
<div id="Building1PerSec" class="label">1</div>
</div>
<div>
<div class="label">Quantity:</div>
<div id="Building1Qty" class="label">0</div>
</div>
</div>
<div id="Building2">
<input type="button" value="Taco Stand" onclick="Build(1);">
<div>
<div class="label">Cost:</div>
<div id="Building2Cost" class="label">10</div>
</div>
<div>
<div class="label">Per Sec:</div>
<div id="Building2PerSec" class="label">1</div>
</div>
<div>
<div class="label">Quantity:</div>
<div id="Building2Qty" class="label">0</div>
</div>
</div>
</div>
<div id="upgrades" class="block">
This is where our upgrades will go!
</div>
</div>
</body>
EDIT:
i tried changing the but tit didnt work
buildings[]
to
buildings["Lemonade Stand", "Taco Stand"]
How about,
LoadBuilding("myBuilding", 12, 1);
Because you have this factory function,
function LoadBuilding(name, cost, persec) {
var cur = buildings.length;
buildings[cur] = new Building();
buildings[cur].Name = name;
buildings[cur].Cost = cost;
buildings[cur].PerSec = persec;
}
You could build an array of Building objects then iterate through them using a while loop.
See JSFIDDLE, or attached code.
Let me know if that helps.
class Building {
constructor(name, cost, persec) {
this.name = name;
this.cost = cost;
this.persec = persec;
}
}
var buildings = [];
buildings.push(new Building('Building One', '$10', '1'));
buildings.push(new Building('Building Two', '$20', '0.5'));
buildings.push(new Building('Building Three', '$25', '2'));
var count = 0;
while(count < buildings.length) {
document.getElementById('stores').innerHTML += '<p>' + buildings[count].name + '<br />' + buildings[count].cost + '<br />' + buildings[count].persec + '</p>';
count++;
}
<div id="stores">
</div>
I am calling a function using onClick inside button. The called function is inside an object and it is getting called each second using setTimeout. But callback function is not getting called by setTimeout and works for just first call.
if i do not use object and use a encapsulating function that returns startPomadoro function, then its working.
###HTML Code ##########
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
### JS COde
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText:'',
startPomodoro: function(){
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if(this.countPomadoro<pomadoroTimeInMinutes){
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
this.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
this.countPomadoro++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
if(this.countBreak<breakInMnutes){
var minutesLeftBreak = this.breakInMinutes - this.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
this.countBreak++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
this.currentTimerText=" Break Time is UP. ";
this.displayPomadoro();
}
}
},
displayPomadoro: function(){
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent=this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
You had a problem with this not being what you think, when function was called from setTimeout. Try something like this:
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText: '',
startPomodoro: function() {
var that = this;
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if (this.countPomadoro < pomadoroTimeInMinutes) {
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
that.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
that.countPomadoro++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
if (that.countBreak < breakInMinutes) {
var minutesLeftBreak = that.breakInMinutes - that.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
that.countBreak++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
that.currentTimerText = " Break Time is UP. ";
that.displayPomadoro();
}
}
},
displayPomadoro: function() {
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent = this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
PS. You also had a typo breakInMnutes instead of breakInMinutes.
I have solved this problem by moving away from jquery , and simply
setting event handler on divs by wrapping each image inside one div using
JavaScript. Below is the sample code.
//code
handler.divs.forEach(function(div){
var img = document.getElementById(div);
img.onclick = function(){
var id = parseInt(img.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" div clicked " + id + " u p " + userPattern);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" if ");
handleWrongInput();
} else if(userPattern.length === simonGame.PATTERN.length){
setTimeout(function(){simonGame.patternGen({result:"success"})},1200);
}
}
});
console.log(" up " + userPattern + " SGP " + simonGame.PATTERN);
I am having some trouble. I am working within Business Catalyst which stores dynamic user-submitted data and allows me to output it in whatever way I need.
I have created a series of Web Apps that work together to allow users to take quizzes. Currently I am receiving an error message 'Uncaught TypeError: Cannot read property 'questionText' of undefined'
How my code is working currently:
A user submits a form with quiz/survey data.
They are directed to a new page that runs a search for the most recent quiz/survey submission unique to their user.
The data is output on the page within a div.
A function reads the data and builds the page content accordingly to display the correct quiz/survey results.
The data that is submitted is output in the following format. Note that the {tags} are Business Catalysts way of outputting dynamic information - the {tag} is replaced with the user-submitted data on the page. Also note that I have only shown the data for 3 questions, there are up to 15 in total.
var quizSurvey = "{tag_quiz/survey}";
var w = window.innerWidth;
function Question(questionNumber, questionText, answerType, answerA, answerB, answerC, answerD, correctAnswer, userMultichoice, userTF, userSRating, userSSAnswer, qPassFail) {
this.questionNumber = questionNumber;
this.questionText = questionText;
this.answerType = answerType;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.answerD = answerD;
this.correctAnswer = correctAnswer;
this.userMultichoice = userMultichoice;
this.userTF = userTF;
this.userSRating = userSRating;
this.userSSAnswer = userSSAnswer;
this.qPassFail = qPassFail;
};
var question = new Array();
question[1] = new Question("1", "{tag_q1-question}", "{tag_q1-answer-type}", "{tag_q1-multichoice-a}", "{tag_q1-multichoice-b}", "{tag_q1-multichoice-c}", "{tag_q1-multichoice-d}", "{tag_q1-correct-answer}", "{tag_q-multichoice-1}", "{tag_q-t/f-1}", "{tag_s-ratings-1}", "{tag_s-shortanswer-1}", "{tag_q1-pass/fail}");
question[2] = new Question("2", "{tag_q2-question}", "{tag_q2-answer-type}", "{tag_q2-multichoice-a}", "{tag_q2-multichoice-b}", "{tag_q2-multichoice-c}", "{tag_q2-multichoice-d}", "{tag_q2-correct-answer}", "{tag_q-multichoice-2}", "{tag_q-t/f-2}", "{tag_s-ratings-2}", "{tag_s-shortanswer-2}", "{tag_q2-pass/fail}");
question[3] = new Question("3", "{tag_q3-question}", "{tag_q3-answer-type}", "{tag_q3-multichoice-a}", "{tag_q3-multichoice-b}", "{tag_q3-multichoice-c}", "{tag_q3-multichoice-d}", "{tag_q3-correct-answer}", "{tag_q-multichoice-3}", "{tag_q-t/f-3}", "{tag_s-ratings-3}", "{tag_s-shortanswer-3}", "{tag_q3-pass/fail}");
var userScore = "{tag_total score}";
var passingScore = "{tag_required score to pass}";
var showAnswers = "{tag_show answers}";
So now that you see how the Data is stored, here is the code for the page that it is output on. Note that I left out Step 2, the code that runs the search - I know this works, so I didn't think you would need to see it.
<div class="row">
<div class="small-12 columns">
<div class="quiz-survey-search" id="qs-results" style="display: block;"> {module_webappscustomer,19627,l,,,_self,true,1,true,1} </div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<div class="correct" id="correct" style="display: none;">
<h2 id="quiz-headline-1" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">Good work completing this chapter!<br />
Your score is:</h4>
<div class="large-score" id="score-1"></div>
</div>
<div class="incorrect" id="incorrect" style="display: none;">
<h2 id="quiz-headline-2" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">You did not achieve the required passing score. Please review the materials and take the quiz again to complete this chapter.</h4>
<div class="large-score" id="score-2" style="margin:3rem 0rem;"></div>
</div>
<div class="survey" id="survey" style="display: none;">
<h2>Thank you for completing the survey.</h2>
<h4>Your answers have been submitted.</h4></div>
</div>
<div id="correct-answers" style="display: none;">
<h3 style="text-decoration: underline;">Correct Answers</h3>
<p style="font-weight: bold;">Although you passed the quiz you had one or more answers that were incorrect.
Below are the correct answers.</p>
<div class="row">
<div id="incorrectQuestions"></div>
</div>
</div>
</div>
<script>
var quizsurveyDiv = document.getElementById('qs-results').innerHTML;
if (quizsurveyDiv == " ") {
var element = '{module_url,AllIDs}';
var arrayOfStrings = element.split("-");
document.getElementById('CAT_Custom_206').value = arrayOfStrings[0];
document.getElementById('CAT_Custom_2').value = arrayOfStrings[1];
document.getElementById('CAT_Custom_3').value = arrayOfStrings[2];
catcustomcontentform9225.submit();
} else {
if (quizSurvey == "Quiz") {
var qNumber = 0;
var qNumbers = function() {
for (i = 0; i <= 14; i++) {
if (question[i].questionText !== "") {
qNumber = qNumber + 1;
console.log('here - ' + qNumber);
};
};
};
var writeDivs = function() {
var incorrectQDiv = "";
for (i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
incorrectQDiv = document.getElementById('incorrectQuestions').innerHTML;
document.getElementById('incorrectQuestions').innerHTML = incorrectQDiv + "<div class='small-12 medium-6 columns incorrectQ' id='incorrectQ-" + question[i].questionNumber + "'>Hi!!</div>";
console.log('here2 - ' + qNumber);
} else if (question[i].qPassFail == "1") {
};
};
};
var writeQContent = function() {
for (var i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
if (question[i].answerType == "True/False") {
var qUserAnswer = question[i].userTF;
} else {
qUserAnswer = question[i].userMultichoice;
};
document.getElementById('incorrectQ-' + question[i].questionNumber).innerHTML = "<p><span class='pinkNum'>" + question[i].questionNumber + "</span>" + question[i].questionText + '</p><div class="row"><div class="small-12 small-push-12 medium-6 columns"><p><span class="pink-title">Your Answer: ' + qUserAnswer + '</span><br/><div id="incorrectA-' + question[i].questionNumber + '"></div></p></div><div class="small-12 small-pull-12 medium-6 columns"><p><span class="pink-title">Correct Answer: ' + question[i].correctAnswer + '</span><div id="correctA-' + question[i].questionNumber + '"></div></p></div></div>';
};
if (question[i].qPassFail == "0" && question[i].answerType == "Multiple Choice") {
var correctADiv = "correctA-" + question[i].questionNumber; console.log(correctADiv);
if (question[i].correctAnswer == "A") {
document.getElementById(correctADiv).innerHTML = question[i].answerA;
} else if (question[i].correctAnswer == "B") {
document.getElementById(correctADiv).innerHTML = question[i].answerB;
} else if (question[i].correctAnswer == "C") {
document.getElementById(correctADiv).innerHTML = question[i].answerC;
} else {
document.getElementById(correctADiv).innerHTML = question[i].answerD;
};
};
};
};
var showTheAnswers = function() {
if (quizPassFail == "1") {
document.getElementById('quiz-headline-1').innerHTML = "You passed the quiz: " + quizName;
document.getElementById('score-1').innerHTML = '<span class="large-score">' + totalScore + '%</span>';
document.getElementById('correct').style.display = "block";
if (showAnswers == "1") {
if (totalScore != "100") {
document.getElementById('correct-answers').style.display = "block";
} else if (showAnswers != "1" || totalScore == "100") {
document.getElementById('correct-answers').style.display = "none";
};
};
} else {
document.getElementById('quiz-headline-2').innerHTML = "Unfortunately you did not pass the quiz: " + quizName ;
document.getElementById('score-2').innerHTML = '<div class="hide-for-small medium-1 large-2 columns"> </div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="userScore"></span><br/>Your Score</p></div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="requiredScore"></span><br />Required Score</p></div><div class="hide-for-small medium-1 large-2 columns"> </div>';
innerScores();
document.getElementById('incorrect').style.display = "block";
};
};
var innerScores = function() {
document.getElementById('userScore').innerHTML = totalScore + "%";
document.getElementById('requiredScore').innerHTML = requiredScore + "%";
console.log('innerScores');
};
if (showAnswers == "1" && totalScore != "100") {
qNumbers();
writeDivs();
writeQContent();
showTheAnswers();
} else if (showAnswers == "0" && totalScore != "100") {
showTheAnswers();
} else {
showTheAnswers();
}
} else if (quizSurvey == "Survey") {
document.getElementById('survey').style.display = "block";
};
courseCompletePass();
};
Thank you for any and all possible help. This has been an extremely difficult coding process and any help would be greatly appreciated!
how do you change a inner id with js and keep it the same id num (e.g hey1, bob2)
my js code
var obj = document.getElementById("chat").cloneNode(true);
var obj1 = document.getElementById("ch");
var obj2 = document.getElementById("chatbox");
var p = $(".chat");
var offset = p.offset();
num = num + 1;
if (num <=15) {
obj.id = obj.id + num; <--- **changing the id (this one works fine but the other two dont**
obj1.id = obj1.id + num; <--- changing the id
obj2.id = obj2.id + num; <--- changing the id
document.body.appendChild(obj);
document.body.appendChild(obj1);
document.body.appendChild(obj2);
var left = offset.left + 275;
document.getElementById("chat").style.left = left + "px";
tell me if i am doing it wrong but this was the easiest way i thought off
(ps i am a beginner at javascript)
thanks to all that try to help...
Edit
ok i clone this
<div class="chat" id="chat">
<div id="ch" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
and everytime it clones it changes the id of chat,ch and chatbox but keeping the original the same
like so...
clone1
<div class="chat" id="chat1">
<div id="ch1" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox1">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
Clone2
<div class="chat" id="chat2">
<div id="ch2" class="ch">
<h2>Chat</h2></div>
<div class="chatbox" id="chatbox2">
<div class="messages"></div>
<textarea id="message" class="chatinp"
rows="3" cols="27"></textarea>
<button class="send">Send</button></div>
</div>
Not sure, but if I'm right, you're trying to create a new 'chatnode'. You'll have to traverse the childNodes array of the node you cloned to change id's. Try something like:
function cloneChat(){
var obj = document.getElementById("chat").cloneNode(true),
children = obj.childNodes
;
num += 1;
obj.id = obj.id+num;
if (num<16){
changeId(children,num);
}
//now appending obj to the document.body should be sufficient
document.body.appendChild(obj);
//change id recursively
function changeId(nodes, n){
for (var i=0;i<nodes.length;i=i+1){
if (nodes[i].childNodes){
changeId(nodes[i].childNodes,n);
}
if(nodes[i].id && /^ch$|^chatbox$/i.test(nodes[i].id)) {
nodes[i].id += String(n);
}
}
}
}
See this jsfiddle for a working example
Furthermore, this code won't work:
var p = $(".chat");
var offset = p.offset();
Because $(".chat") returns a list of nodes, where every node has it's own offset.
You seem to be using jQuery, so I suggest adding a 'jQuery' tag to your question. Maybe some jQuery whizzkid has a solution to offer.
In jQuery try to use
element.attr("id","newId");
See: http://api.jquery.com/attr/
How about this function?
function appendMe() {
var elementsToClone = ["chat"]; //Parent Elements to clone. This is the class name as well as the id
var childrenToHandle = new Array();
childrenToHandle["chat"] = ["ch"]; //Child elements mapping to keep sync. This is the class name as well as the id. Here we say that for the parent element chat, the inner elements to keep in sync is ch
var itemCount = 0;
for(i = 0; i < elementsToClone.length; i++) {
var refObj = document.getElementById(elementsToClone[i]);
if(refObj) {
$("." + elementsToClone[i]).each(
function() {
if(this.id.match(/\d+$/g)) {
itemCount = this.id.match(/\d+$/g);
}
}
);
var newObj = refObj.cloneNode(true);
newObj.id = elementsToClone[i] + ++itemCount;
var childrenArray = childrenToHandle[elementsToClone[i]];
if(childrenArray) {
$(childrenArray).each(
function() {
$(newObj).find("." + this).attr("id", this + itemCount);
}
);
}
document.body.appendChild(newObj);
}
}
}
Since you're already using jQuery in your code, how about:
var $obj = $("#chat").clone(),
$obj1 = obj.find("#ch"),
$obj2 = obj.find("#chatbox");
var p = $(".chat"),
offset = p.offset();
num = num + 1;
if (num <= 15) {
$obj.attr('id', $obj.attr('id') + num);
$obj1.attr('id', $obj1.attr('id') + num);
$obj2.attr('id', $obj2.attr('id') + num);
$('body').append(obj);
var newLeft = offset.left + 275;
$('#chat').css({
left: newLeft
});
}