Scoring a Javascript Quiz Script - javascript

Hi I some javascript code written to quiz the user on 5 questions and then in theory output their score. As far as I can tell the questions are being scored, I just can't figure out how to output the response. I am having no issues fetching the correct html elements and displaying them. I believe the issue is in the looping elements of the window.onload function. The code is below,
<script type="text/javascript">
var rand = 0;
var right = 0;
window.onload = function () {
reset();
Rrand();
var rangQ = document.getElementById('area').getElementsByClassName('divide');
correct = document.getElementsByTagName('a'), i = 0;
for (i; i < correct.length; i++) {
if (correct[i].className == 'correct') {
correct[i].onclick = function () {
right++;
reset();
Rrand();
}
}
else if (correct[i].className != 'correct') {
correct[i].onclick = function () {
right--;
reset();
Rrand();
}
}
}
}
function Rrand() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
rangQ[rand].style.display = '';
rand++;
}
function reset() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
for (var i = 0; i < rangQ.length; i++) {
rangQ[i].style.display = 'none';
}
}
document.write(right);
</script>

window.onload is not executed immidiately. you are writing output, but variable right is changed after that.
you need to either move line
document.write(right);
into window.onload as last line (or after loop) or figure out other way that will be best for you

Related

Change label text every two seconds and wait executing following cos [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i need some code to change label text every two seconds for example on page load label text is "100" after two seconds is"200" after two more seconds is "300" and ....
i have an array for this meaning,my code is like this:
<script type="text/javascript">
function func_code() {
var codes = null;
var code_arr = null;
var j = null;
var i = null;
codes = "100000,100004,100007,100009,100012";
code_arr = codes.split(',');
var len = code_arr.length;
for (j = 0; j <= len; j++) {
for (i = code_arr[j]; i <= code_arr[j + 1]; i++) {
setTimeout(function () { change_number(i) }, 2000);
******wait here for 2 seconds*******
}
}
// document.getElementById('counter').innerHTML = 5000000;
}
function change_number(i) {
document.getElementById('counter').innerHTML = i;
}
</script>
<label id="counter">123</label>
I'm not sure that I understood correctly..
Maybe you need something like this?
function func_code() {
var codes = "100000,100004,100007,100009,100012";
var code_arr = codes.split(',');
for (i = 0;i < code_arr.length;i++) {
(function(i){
setTimeout(function(){
change_number(code_arr[i]);
}, 2000*i);
})(i)
}
}
function change_number(i) {
document.getElementById('counter').innerHTML = i;
}
func_code();
<div id="counter"></div>
<script>
setInterval(function () { change_number() }, 2000);
function change_number(){
var elem = document.getElementById('counter');
var val = elem.innerHTML;
elem.innerHTML = parseInt(val)+100;
}
</script>
<label id="counter">100</label>
var x = 100;
var myCounter = setInterval(function(){
console.log(x);
x = x+100;
if(x == 110){
clearInterval(myCounter); //to clear interval
}
}, 2000);
A recursive solution would look something like this:
var len = code_arr.length;
function looper(j,len) {
if (j<=len) {
for (i = code_arr[j]; i <= code_arr[j + 1]; i++) {
setTimeout(function () {
change_number(i);
looper(j+1,len); // call the function again
}, 2000);
} // for
} // if
} // function
looper(0,len);

Quiz in Javascript with Arrays?

So, I'm trying to create a quiz in Javascript, by using number ids of the text inputs in HTML, then running a for loop and if to compare the input to the answer in an answers array.
In Html:
<form>
China<input type="text" id="0"><br>
France<input type="text" id="1"><br>
Japan<input type="text" id="2"><br>
<input type="button" id="submitt" value="submit">
</form>
In Javascript:
var answers = ["Beijing", "Paris", "Tokyo",];
$("#submitt").click(function() {
var totalYes=0;
function checkAnswers() {
for(var i=0; i<answers.length; i++) {
var userAnswer = document.getElementById(i);
if(userAnswer.value===answers[i]) {
totalYes++;
}
}
}
alert(totalYes);
checkAnswers();
});
But the code doesn't add 1 to the variable totalYes (questions correct). I've tried totalYes+=1 and totalYes + 1 as well. The alert of totalYes shows up as 0 everytime.
But I know that's the only part not working because when I change totalYes to correct and incorrect alerts, it works:
var answers = ["Beijing", "Paris", "Tokyo",];
$("#submitt").click(function() {
var totalYes=0;
function checkAnswers() {
for(var i=0; i<answers.length; i++) {
var userAnswer = document.getElementById(i);
if(userAnswer.value===answers[i]) {
alert("Correct!");
} else {
alert("Incorrect!");
}
}
}
alert(totalYes);
checkAnswers();
});
Please help?
jsFiddle Demo
NOTE: Because totalYes is a global variable you'll want to reset it to 0 after you show how many the user got right
JS
var answers = ["Beijing", "Paris", "Tokyo", ];
var totalYes = 0;
$("#submitt").click(function (e) {
checkAnswers();
alert(totalYes);
e.preventDefault();
});
function checkAnswers() {
for (var i = 0; i < answers.length; i++) {
var userAnswer = document.getElementById(i);
if (userAnswer.value === answers[i]) {
totalYes++;
}
}
}
Side Note: This would be the easy test to cheat on...simply view source and you can see the JavaScript answers. Perhaps you should toLower() the text and then md5 or sha1 the answers. Then simply do the same when checking them
jsFiddle Demo
var answers = ["feecd450f4886bbed257e222fcf7609cbdd57a64", "3c4bd4d0d0d1e076ce617723edd6a73afc9126ab", "0f1aae8b8398c20f81e1c36e349a7880c9234c63", ];
var totalYes = 0;
$("#submitt").click(function (e) {
checkAnswers();
alert(totalYes);
e.preventDefault();
totalYes = 0;
});
function checkAnswers() {
for (var i = 0; i < answers.length; i++) {
var userAnswer = document.getElementById(i);
if (Sha1.hash(userAnswer.value.toLowerCase()) === answers[i]) {
totalYes++;
}
}
}
Note: You will see some sha1 code this code was taken from http://www.movable-type.co.uk/scripts/sha1.html#code
This will make it impossible without a rainbow table to simply view source to get the answer, I hope this is helpful in some small way
Extra note: Because you are using a for loop for each question, any answer can be put into any textbox. Example: Paris can be put in the textbox next to China and you'll still get 1 right.
The order of calling functions is not correct. You are first alerting your variable and then start counting correct answers. Change to:
$("#submitt").click(function() {
var totalYes=0;
function checkAnswers() {
for(var i=0; i<answers.length; i++) {
var userAnswer = document.getElementById(i);
if(userAnswer.value===answers[i]) {
totalYes++;
}
}
}
checkAnswers(); // check answers at the first place
alert(totalYes);
});

How to disable buttons after x amount of clicks in js?

I am trying to use Javascript to disable a button after it is clicked x amount of times. For simplicity sake lets say x = 2 for now. I cannot seem to get the counter to increment. Thank You for any help!
var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
coke.onclick = function(){
var count =0;
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}
Where "coke" is the element ID. If i get rid of the if statement and just have coke.disabled = true, of course it works and disables after one click. I'm sure there is a core concept I am missing.
Thank You
This is happening because each time the onclick event is fired, your var count is being assigned to 0, so it will never be greater than or equal to one in your function. If you initialize the count var outside of the onclick function, it will behave as expected.
window.onload = function () {
var count = 0;
coke.onclick = function(){
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}
You need to define count outside the scope of your onclick function:
var $ = function (id) {
return document.getElementById(id);
}
var count = 0; // set initial count to 0
window.onload = function () {
coke.onclick = function(){
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}

Javascript Click Function Broken in Gallery Script

I'm trying to create a gallery script with JS (I've only been learning for a week so please excuse if I've made any ridiculous mistakes!). When I run the code, I get an error for controlLeft.onclick = changeImage(--);, saying ( is an unexpected token.
By my untrained eye everything should be fine, but evidently not. What have I done wrong here:
//Javascript Image Changer
var currentImage = document.getElementById("currentImage");
var imageArray = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg"];
var imageIndex= 0;
function changeImage(param){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex[param];
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = changeImage(--);
controlRight.onclick = changeImage(++);
You can't just pass operators around like other things. Even in a programming language with higher-order functions the same thing usually does not apply to operators.
Besides that, onclick expects a function - not the result of a function call.
Here's a snippet that is likely to work:
function changeImage(mod){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex += mod;
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = function() { changeImage(-1); };
controlRight.onclick function() { changeImage(1); };
Just make a slight modification:
controlLeft.onclick = function() {
changeImage('back');
};
controlRight.onclick = function() {
changeImage('forward');
};

Javascript simple UDF

I'm now developing one JS UDF which seems following coding.
<script>
<!--
function alertmsg()
{
alert("Hello World");
}
for(p=1; p <= 2; p++)
{
alertmsg();
}
-->
</script>
Normally, Alert Msg will be came out two times because of loop count is 2. What I want is Alert Msg will be came out only one time even loop count is 3. Any idea will be appreciated in advance.
You only want to execute the piece of code once in the loop? Do something like this:
var executed = false;
for(var i = 1; i <= 2; i++)
{
if (!executed) {
alertmsg();
executed = true;
}
}
Or perhaps this?
<script type="text/javascript">
function alertmsg() {
alert("Hello World");
}
for (var p = 0; p < 3; p++) {
if (p == 2) {
alertmsg();
}
}
</script>

Categories