jeudi 27 octobre 2016

How to store and re-use text input values and variable values that use Math.random()?

Okay, so I'm trying to create a quiz application for revision purposes that asks a random question from a list of questions, takes a text input as the users answer to the question, and then compares it to the actual answer to the question. The code I have used is:

var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
    document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
    document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;

var answerValidation = function(correctAnswer, userAnswer) {
    correctAnswer = htmlModule[ranPropName][1];
    userAnswer = document.getElementById("submit").value;;

    if(userAnswer === correctAnswer) {
    document.getElementById("rightWrong").style.backgroundColor = "green";
    } else {
    document.getElementById("rightWrong").style.backgroundColor = "red";
    }

};

The variable "htmlModule" refers to the object in which the questions and their answers are stored. Each question and answer pair is stored inside an array that is the value of its property, the property simply being a key used to reference each pair e.g. htmlQ1, htmlQ2 etc.

The main problem I seem to be having is that my 'if' statement comparing the actual answer and the user answer won't evaluate to 'true'. I know this because the background colour of the div element "rightWrong" only ever turns red, even when I've definitely typed in a correct answer at which point it should turn green. My assumption is that either the text input isn't being stored for some reason, or the value of the variable 'ranPropName' that uses Math.random() is changing due to the use of Math.method(), but I'm stuck as to how to remedy either potential problem. Thanks in advance for any replies.




Aucun commentaire:

Enregistrer un commentaire