I am new to javascript. I am making a flashcard program. For some reason, despite defining the variable lastPress as global, lastPress seems to return undefined. However, it is not resulting in an error in JSHint. Here's my code:
var i = 0;
var questions = ["1: Was the human migration caused by an ice age?", "True"];
var answer = [true, true];
var lastPress;
document.getElementById("question").innerHTML = questions[i];
function itsTrue() {
lastPress = true;
}
function itsFalse() {
lastPress = false;
}
function getAns() {
if (answer[i] == lastPress) {
document.getElementById("ans").innerHTML = "You're correct! The answer was " + lastPress;
}
else {
document.getElementById("ans").innerHTML = "We're sorry, but that is not correct. You said " + lastPress + ". The answer was " + answer[i];
}
i++;
document.getElementById("question").innerHTML = questions[i];
}
document.getElementById("true").onclick = function(){itsTrue()};
document.getElementById("true").onclick = function(){getAns()};
document.getElementById("false").onclick = function(){itsFalse()};
document.getElementById("false").onclick = function(){getAns()};
<!DOCTYPE HTML>
<html>
<head>
<title>Flash cards</title>
</head>
<body>
<p id="question">This is where the question shows up</p>
<p id="ans">This is where the result will show up</p>
<button type="button" id="true">True</button>
<button type="button" id="false">False</button>
</body>
</html>
if you want to define multiple functions to the same click event: also, after the second press on your true false buttons i is incremented to 2 thus questions[2] is undefined
var i = 0;
var questions = ["1: Was the human migration caused by an ice age?", "True"];
var answer = [true, true];
var lastPress;
document.getElementById("question").innerHTML = questions[i];
function itsTrue() {
console.log('true')
lastPress = true;
}
function itsFalse() {
console.log('false');
lastPress = false;
}
function getAns() {
if (answer[i] == lastPress) {
document.getElementById("ans").innerHTML = "You're correct! The answer was " + lastPress;
}
else {
document.getElementById("ans").innerHTML = "We're sorry, but that is not correct. You said " + lastPress + ". The answer was " + answer[i];
}
i++;
console.log(i);
document.getElementById("question").innerHTML = questions[i];
}
document.getElementById("true").onclick = function(){itsTrue();getAns();};
//document.getElementById("true").onclick = function(){getAns()};
document.getElementById("false").onclick = function(){itsFalse(),getAns();};
// document.getElementById("false").onclick = function(){getAns()};
<!DOCTYPE HTML>
<html>
<head>
<title>Flash cards</title>
</head>
<body>
<p id="question">This is where the question shows up</p>
<p id="ans">This is where the result will show up</p>
<button type="button" id="true">True</button>
<button type="button" id="false">False</button>
</body>
</html>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments