JavaScript Alert Box Popup Issue - javascript

I am having an issue with an Alert Box not appearing on the screen after I click a submit button. I have searched this forum and online for answers and I don't see what is wrong with my code. As with most of my issues, the solution is probably a simple fix but I can't seem to find the issue after going through my code. Any help is appreciated.
javascript code
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
}
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementById('quizclock').value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
function showQuiz() {
document.getElementById("quiztable").style.visibility="visible";
document.quiz.start.disabled = true;
document.quiz.stop.disabled = false;
}
function hideQuiz() {
document.getElementById("quiztable").style.visibility="hidden";
}
function gradeQuiz() {
correct=0;
if (document.quiz.q1[1].checked) correct++;
if (document.quiz.q2[3].checked) correct++;
if (document.quiz.q3[0].checked) correct++;
if (document.quiz.q4[3].checked) correct++;
if (document.quiz.q5[2].checked) correct++;
document.getElementById("cor1").style.backgroundColor="yellow";
document.getElementById("cor2").style.backgroundColor="yellow";
document.getElementById("cor3").style.backgroundColor="yellow";
document.getElementById("cor4").style.backgroundColor="yellow";
document.getElementById("cor5").style.backgroundColor="yellow";
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=true;
return correct;
}
html for button that pops up the alert
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>

Probably you have a variable undefined, check this working demo
function gradeQuiz() {
return 'something';
}
var clockId, i = timer = 0;
clockId = setInterval(function() {
i++;
$('h2').text(i);
}, 200);
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have ' + correctAns + ' correct of 5 in ' + timer + ' seconds');
}
$('button').on('click', stopClock);
http://jsbin.com/toyibekivu/edit?html,js,output

You need to define your variables and use seconds in alert.
Change your functions to:
var clockId;
var seconds = 0;
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + seconds + 'seconds');
}
function startClock() {
showQuiz();
seconds = 0;
clockId=setInterval (runClock, 1000);
}

If you remove
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
from your stopClock() function no alert will appear on the screen.

Related

Issue linking images to dynamically created jquery elements

So, I'm very new, so apologies if this is a silly question. I have worked out a Trivia Quiz for my learning to code classes I'm taking. I want to display an image on the confirmation screen that shows whether the user was right or wrong. I think the code is correct-ish? I'm not sure what isn't working.
I left out the main Question and answer object for space. Sorry if I didn't format this ideally? I'm still kinda figuring out how things work here.
Here is my code for reference:
//array to help me iterate and insert images
var imgArray = ["question1", "question2", "question3", "question4", "question5", "question6", "question7", "question8", "question9", "question10", "question11", "question12", "question13"];
var currentQuestion = 0;
var win = 0;
var lose = 0;
var unanswered = 0;
var time = 30;
//set up divs to contain our info
var rightDiv = $("<div class='rightAns'></div>");
var timerDiv = $("<div class='countdown'><h3></h3></div>");
var questionDiv = $("<div class='question'><h1></h1></div><br>");
var answerDiv = $("<div class='answers'></div>");
//object keys to return questions in order
var keys = Object.keys(questions);
var key = keys[n];
var n = 0;
//function to setup and restart game
function reset() {
$("#start-button").hide("slow");
$("#start-here").hide("slow");
win = 0;
lose = 0;
unanswered = 0;
n = 0;
key = keys[n];
currentQuestion = 0;
$("#question-block").empty();
var reset = function () {
time = 30;
$(".rightAns").empty();
$(".rightAns").remove();
// $("#image").empty();
$("#time-remaining").append(timerDiv);
$(".countdown h3").html("Time Remaining: " + time);
$("#question-block").append(questionDiv);
$("#question-block").append(answerDiv);
}
reset();
//function to show questions
function showQuestion() {
$(".question h1").html(questions[key].question);
for (var i = 0; i < questions[key].answers.length; i++) {
$(".answers").append("<button class='answer btn btn-danger btn-lg m-1'>" + questions[key].answers[i] + "</button>");
}
$(".answers button").on("click", function () {
var selected = $(this).text();
//if then to check question correctness
if (selected === questions[key].correct) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("That's Correct!!");
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
win++;
currentQuestion++;
} else {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("Nope! The correct answer was: " + questions[key].correct);
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
lose++;
currentQuestion++;
}
n++;
key = keys[n];
//checking to see if there are more questions left
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
});
}
showQuestion();
var counter = setInterval(count, 1000);
//show time remaining for each question
function count() {
time--;
$(".countdown h3").html("Time Remaining: " + time);
if (time < 1) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").html("You took too long! The correct answer was: " + questions[key].correct);
unanswered++;
n++;
key = keys[n];
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
}
}
function checkForLast() {
if (key === undefined) {
return true;
}
return false;
}
//timer for the message after you choose your answer
function countReset() {
counter = setInterval(count, 1000);
}
//showthe final score screen
function finalScore() {
$(".rightAns").remove();
$("#image").empty();
$("#question-block").prepend("<h2>Unanswered: " + unanswered + "</h2>");
$("#question-block").prepend("<h2>Incorrect: " + lose + "</h2>");
$("#question-block").prepend("<h2>Correct: " + win + "</h2>");
$("#start-button").show();
$("#start-here").show();
}
};
//function to start game on button click
$(document).on("click", "#start-button", reset);
});
After tinkering for a bit, I dropped the "." at the beginning of the call and added the .jpg to the section after imgArray[currentQuestion]. That solved it. Thanks for the suggestions.

Scope of undefined in 2nd round of a Javascript & JQuery Trivia game

My game works until summary page start link is clicked. Then I get undefined variables when trying to play again.
I'm new to JS so I'm sure it is a stupid user error and not handling scope correctly.
If I comment the location.reload at the bottom of the javascript it works just fine after the timer is up, but the coding assignment wants us to not do a refresh. I appreciate any help!
$(document).ready(function() {
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0;
var answered = false;
var correct;
var start = $(".start").html("Start Game");
start.on("click", startGame);
var triviaQandA = [{
question: "What is the fastest animal?",
answer: ["cheetah", "turtle", "giraffe", "elephant"],
correct: "0",
image: ("assets/images/circle.png")
}, {
question: "When you are blue you turn?",
answer: ["red", "green", "blue", "yellow"],
correct: "2",
image: ("assets/images/dot.jpg")
}];
function startGame() {
$(".start").hide();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA();
}
function loadQandA() {
answered = false;
timeRemaining = 16;
intervalID = setInterval(timer, 1000);
if (answered === false) {
timer();
}
correct = triviaQandA[indexQandA].correct;
var question = triviaQandA[indexQandA].question;
$(".question").html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaQandA[indexQandA].answer[i];
$(".answers").append("<h4 class = answersAll id =" + i + ">" + answer + "</h4>");
}
$("h4").click(function() {
var id = $(this).attr("id");
if (id === correct) {
answered = true;
$(".question").text("The answer is: " + triviaQandA[indexQandA].answer[correct]);
correctAnswer();
} else {
answered = true;
$(".question").text("You chose: " + triviaQandA[indexQandA].answer[id] + " the correct answer is: " + triviaQandA[indexQandA].answer[correct]);
incorrectAnswer();
}
console.log(correct);
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
clearInterval(intervalID);
$(".question").text("The correct answer is: " + triviaQandA[indexQandA].answer[correct]);
unAnswered();
} else if (answered === true) {
clearInterval(intervalID);
} else {
timeRemaining--;
$(".timeRemaining").text("You have " + timeRemaining);
}
}
function correctAnswer() {
correctAnswers++;
$(".timeRemaining").text("You are spot on!!!").css({
"color": "#3d414f"
});
reset();
}
function incorrectAnswer() {
incorrectAnswers++;
$(".timeRemaining").text("You are sooo wrong").css({
"color": "#3d414f"
});
reset();
}
function unAnswered() {
unansweredQuestions++;
$(".timeRemaining").text("You didn't choose anything...").css({
"color": "#3d414f"
});
reset();
}
function reset() {
$(".answersAll").remove();
$(".answers").append("<img class=answerImage width='150' height='150' src='" + triviaQandA[indexQandA].image + "'>");
indexQandA++;
if (indexQandA < triviaQandA.length) {
setTimeout(function() {
loadQandA();
$(".answerImage").remove();
}, 2000);
} else {
setTimeout(function() {
$(".question").remove();
$(".timeRemaining").remove();
$(".answerImage").remove();
$(".answers").append("<h4 class = answersAll end>Correct answers: " + correctAnswers + "</h4>");
$(".answers").append("<h4 class = answersAll end>Wrong answers: " + incorrectAnswers + "</h4>");
$(".answers").append("<h4 class = answersAll end>Unanswered questions: " + unansweredQuestions + "</h4>");
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
// setTimeout(function() {
// location.reload();
// }, 5000);
var start = $(".start-over").html("Start Game");
start.on("click", startGame);
}, 2000);
}
};
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="start"></div>
<h1>Trivia</h1>
<h5 class="timeRemaining"></h5>
<h3 class="question"></h3>
<div class="answers"></div>
<div class="start-over"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Here's an inline link to my Codepen.
The problem comes from the fact that you increment indexQandA on each question, but never reset it. You need to reset it to 0 when starting a new game - that is, in the else clause of the reset function you need to put indexQandA=0 alongside where you reset the other variables to 0.
There is a further problem when this is done though, the quiz runs ok a second time now, but doesn't display the questions any more. That's because you've removed the .question element during reset. You don't need to do this, you can just hide it, then display it again when the game restarts.
Actually, it transpired there were further problems. I've solved it - run through the game about 5 times in a row with no obvious problems - with the following code (I make no claim that this is the correct code to do it, it's just minimal changes to your existing code to get it to work):
$(document).ready(function() {
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0;
var answered = false;
var correct;
var start = $(".start").html("Start Game");
start.on("click", startGame);
$(".start-over").on("click", startGame);
var triviaQandA = [{
question:"What is the fastest animal?",
answer:["cheetah","turtle","giraffe","elephant"],
correct:"0",
image: ("assets/images/circle.png")
}, {
question:"When you are blue you turn?",
answer:["red","green","blue","yellow"],
correct:"1",
image: ("assets/images/dot.jpg")
}];
function startGame() {
$(".summary").hide();
$(".start").hide();
$(".timeRemaining").show();
$(".question").show();
$(".answers").show();
$(".start-over").hide();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA();
}
function loadQandA() {
answer = [];
answered = false;
timeRemaining = 16;
timer();
intervalID = setInterval(timer, 1000);
/*if (answered === false) {
timer();
}*/
correct = triviaQandA[indexQandA].correct;
var question = triviaQandA[indexQandA].question;
$(".question").html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaQandA[indexQandA].answer[i];
$(".answers").append("<h4 class = answersAll id =" + i + ">" + answer + "</h4>");
}
$("h4").click(function() {
var id = $(this).attr("id");
if (id === correct) {
answered = true;
$(".question").text("The answer is: " + triviaQandA[indexQandA].answer[correct]);
correctAnswer();
} else {
answered = true;
$(".question").text("You chose: " + triviaQandA[indexQandA].answer[id] + " the correct answer is: " + triviaQandA[indexQandA].answer[correct]);
incorrectAnswer();
}
console.log(correct);
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
//clearInterval(intervalID);
$(".question").text("The correct answer is: " + triviaQandA[indexQandA].answer[correct]);
unAnswered();
} else if (answered === true) {
//clearInterval(intervalID);
} else {
timeRemaining--;
$(".timeRemaining").text("You have " + timeRemaining);
}
}
function correctAnswer() {
correctAnswers++;
$(".timeRemaining").text("You are spot on!!!").css({
"color": "#3d414f"
});
reset();
}
function incorrectAnswer() {
incorrectAnswers++;
$(".timeRemaining").text("You are sooo wrong").css({
"color": "#3d414f"
});
reset();
}
function unAnswered() {
unansweredQuestions++;
$(".timeRemaining").text("You didn't choose anything...").css({
"color": "#3d414f"
});
reset();
}
function reset() {
clearInterval(intervalID);
$(".answersAll").remove();
$(".answers").append("<img class=answerImage width='150' height='150' src='" + triviaQandA[indexQandA].image + "'>");
indexQandA++;
if (indexQandA < triviaQandA.length) {
setTimeout(function () {
loadQandA();
$(".answerImage").remove();
}, 2000);
} else {
setTimeout(function() {
$(".summary").show();
$(".question").hide();
$(".timeRemaining").hide();
$(".answers").hide();
$(".start-over").show();
$(".answerImage").remove();
$(".summary").append("<h4 class = answersAll end>Correct answers: " + correctAnswers + "</h4>");
$(".summary").append("<h4 class = answersAll end>Wrong answers: " + incorrectAnswers + "</h4>");
$(".summary").append("<h4 class = answersAll end>Unanswered questions: " + unansweredQuestions + "</h4>");
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
indexQandA=0;
// setTimeout(function() {
// location.reload();
// }, 5000);
$(".start-over").html("Start Game");
start.on("click", startGame);
}, 2000);
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="start"></div>
<h1>Trivia</h1>
<h5 class="timeRemaining"></h5>
<h3 class="question"></h3>
<div class="answers"></div>
<div class="summary"></div>
<div class="start-over"></div>
</body>
</html>
There were 2 main problems with your code as it initially was:
most seriously, you were adding startGame as the click handler for the "start over" button each time the reset function was called. As a result, multiple such handlers were getting added by the time you played a 3rd, 4th, 5th... time, with the result that the startGame function was getting called multiple times, which was why you were getting the answer options printed multiple times. I've fixed this by removing that section of code entirely, and adding the event listener once, on page load.
your timer was also going a bit haywire, as you were calling the timer function manually as well as using setInterval to run it every second, and nor were you always clearing it when the question was answered. I've simplified this greatly, and made it work, just by setting the timer in loadQandA, as before, and clearing it in the reset function.
You will see that I've mainly just commented things out, rather than removed them - this will hopefully make it easier to see what I've removed.

How to display divs in loop using javascript or jquery

This code works perfect for displaying one notification div but i want to display this notification div ten times one after another.
<button onclick="myFunction()">Show Notification</button>
<div id="container">This is First Notification</div>
<script>
function myFunction() {
var x = document.getElementById("container")
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
</script>
You can use recursion
function showTimes(count, times) {
$('#container').show();
$('.info').append("show number" + (count + 1) + "<br>");
console.log('func');
setTimeout(function() {
$('#container').hide()
console.log('count: ' + count + '; times: ' + times);
if (count >= times) {
return;
} else {
setTimeout(showTimes(count + 1, times), 2000);
}
}, 3000);
}
$(document).ready(function() {
showTimes(0, 10);
});
jsfiddle(press RUN at the top)
https://jsfiddle.net/ShinShil/v8ftcnLz/2/

Looping JS Function Until if or else Condition is Met

I have created a function that when called with certain parameters will play out and then either tell the player they won or died based on the math. I have tested the function and it properly works, I set the parameters in the function calling so that the player would win and it displayed the win message alert. But if I increase the monster health to where the player will not win the first time the function is called, the function will not repeat itself as I tried to set up with the "else fight()" (as seen below).
My question is this, how to loop the function with the same parameters as before until the else or else if arguments are met?
Calling the function in HTML:
<a class="button" onclick="javascript:fight(8, 5, 1, 10, 3);">Test fight</a><br>
JS Function:
var playerHealth = 100;
function fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts) {
newPlayerHealth = playerHealth - monsterDmg / armorSts + 2;
newMonsterHealth = monsterHealth - itemDmg / monsterArmor + 2;
if (playerHealth <= 0) {
alert('You died...');
}
else if (newMonsterHealth <= 0) {
alert('You won!');
}
else
{
var newPlayerHealth = playerHealth;
fight(newMonsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts);
}
}
EDIT: Updated function and it says you win no matter how high the monster's damage or health is.
In your code playerHealth was intialize inside function which was resetting players health to 100 in recursive call.
newMonsterHealth was also not persisted considering recursive calls.
<html>
<head>
<script>
var playerHealth = 100;
function fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts) {
playerHealth = playerHealth - Math.floor(monsterDmg / armorSts) ;
console.log("player helath"+playerHealth);
monsterHealth = monsterHealth - Math.floor(itemDmg / monsterArmor) ;
console.log("monster helath"+monsterHealth);
if (playerHealth <= 0) {
alert('You died...');
}
else if (monsterHealth <= 0) {
alert('You won!');
}
else fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts);
}
</script>
</head>
<body>
<a class="button" onclick="javascript:fight(100, 40, 1, 10, 3);">Test fight</a><br>
</body>
</html>
P.S. I removed your +2 logic (I won't understood why you were adding)
You probably need for a recursive function that ends when certain condition will be met.
here is an example:
function recursive(target, i) {
target.innerHTML += '<br>' + i;
console.log('index is', i);
if(i > 100) {
return target.innerHTML += '<br>' + 'END';
}
return recursive(target, ++i);
}
document.addEventListener('DOMContentLoaded', function() {
recursive(document.getElementById('test'), 0)
});
<h1 id="test"></h1>

How to trigger a setInterval function on a user click?

I'm trying to write a JS timer that will be triggered by a user click on the button with id="start".
I've got the timer itself working correctly, but when I try to add code to initiate the timer on the button click (id="start") I break it and am not sure why.
Any help would be greatly appreciated!
Here is the JS code:
$(document).ready(function(){
var count = 0;
$('#start').click(function(){
setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});
$(document).ready(function() {
$('#start').click((function(container) {
var interval;
return function() {
if(interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
})("#timer"));
});
$(document).ready(function() {
var count = 0;
var myInterval = null;
$('#start').click(function(){
myInterval = setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});
When setting your setInterval in the scope of the click handler, try assigning it to a variable to hold the interval declared up a level. This has typically always worked for me.
Not sure exactily what your objective is, but maybe you'd want to try something like this:
var startInterveal;
var timerStarted = false;
var count =0;
$(document).ready(function () {
$('#start').click(function () {
if (!timerStarted) {
timerStarted = true;
count =0;
$(this).attr('disabled', 'disabled');
startInterveal = setInterval('tick();', 1000);
}
});
});
function tick() {
count++;
$('#timer').html(count + ' tacos seconds');
}
Here is a 2nd answer if you really want to go nuts and have something resuable:
$(document).ready(function() {
$('#start').click(overboard("#timer"));
$('#start2').click(overboard("#timer2"));
});
function overboard(container) {
var interval;
return function() {
if (interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
}

Categories

Resources