user3117036
user3117036

Reputation: 83

JavaScript Quiz Not Working

I am trying to make a little quiz to study.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div id="question"></div>
<form>
<input type="text" id="answer">
<button onClick="check()">Check</button>
</form>
<script>
var spanish = new Array("Hola", "Sí", "No");
var english = new Array("Hello", "Yes", "No");
var x = Math.floor(Math.random()*3);

document.getElementById("question").innerHTML = english[x];

var attempt = document.getElementById("answer");
var correct = spanish[x];

function check(){
  if(attempt == correct){
    alert("Correct");
  }else{
    alert("Fail");
  };
};
</script>

</body>
</html>

It is returning Fail no matter if I am right or not. Do you know how to fix this? I looked around but could not figure out what is wrong. Thanks.

Upvotes: -1

Views: 167

Answers (1)

Shomz
Shomz

Reputation: 37701

You need to check for attempt upon clicking the button. You're currently checking it on page load (so it's always an empty string, which is causing correct == attempt to be false). Also, you need to grab the value, not the element.

So, change your function to:

function check() {
    var attempt = document.getElementById("answer").value;
    if (attempt == correct) {
        alert("Correct");
    } else {
        alert("Fail");
    };
};

See here: http://jsfiddle.net/ykZHa/

Upvotes: 2

Related Questions