How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript?

Viewed 673

I'm trying to make a little flashcard quiz game and I'm trying to implement a feature where someone can enter text into an input area and after they press enter the word "Correct" or "Incorrect" is flashed on the screen for 1 second before the input area is blank and the next question get loaded.

Here is a visual of what I am doing:

enter image description here

In particular, this is the HTML code that generates the input text area below:

<form id="answers">
    <input type="text" name="inputtext" id="answer" style="width: 100%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus><br>
</form>

This is the JSON file which is saved as: questionsAndAnswersItalian.json

[{"q":"What is the word for 'where' in Italian?","a":"Dove"},
{"q":"What is the word for 'when' in Italian?","a":"Quando"},
{"q":"What is the word for 'why' in Italian?","a":"Perché"}]

This is the javascript code that I've written which isn't working:

var jsonUrl = "questionsAndAnswersItalian.json";
var qs;
var numCards;
var maxIndex;

function checkAnswer(input, event){
    if(event.keyCode == 13){
        var answer = document.getElementById("answer").value.toLowerCase();
        var questionNumber = 0;
        for(var i = 0; i<jsonUrl.length; i++){
            if(answer == jsonUrl[questionNumber]["a"].toLowerCase()){
                setTimeout(correct_input, 1000);
                input.value = "";
            }else{
                setTimeout(incorrect_input, 1000);
                input.value = "";
            }
            questionNumber++;
        }
    }
}
function correct_input(){
    input.value = "Correct!";
}
function incorrect_input(){
    input.value = "Incorrect!";
}

function init() {
    $.getJSON(jsonUrl, function(jsonObject) {
        qs = jsonObject;
        numCards = qs.length;
        maxIndex = numCards-1;
        displayCard();
    });
}

The functions aren't working as I expected them to and I was wondering if someone could tell me where I am going wrong.

If you need more information to understand what I'm doing here please do not hesitate to ask!

Any help or advice would be much appreciated!

Thank you.

2 Answers
Related