samedi 20 octobre 2018

Javascript - Compare user input value to randomly generated value

I have a function that displays a random word from an array, in a non-repeated way, and a textbox where the user is supposed to type the same generated word.

I tried using a switch statement to validate the user's answer, comparing his input to the randomly generated word, but it is not working.

My question is, is it even possible to compare such things? And if so, how?

This is my code:

        // Generate random, non-repeated word
        const p = document.getElementById("randomWord");
        const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
        let remainingWords = [];
        
        function randomize() {
            if (remainingWords.length === 0) remainingWords = origWords.slice();
            const {
                length
            } = remainingWords;
            const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
            p.textContent = quote;
        }
        randomize();
        
        // Validate answer
        function submit001() {
            var answers = document.getElementById("input001").value.toLowerCase();
            switch (answers, remainingWords) {
                case "":
                    text = "Please write something.";
                    break;
                case answers == remainingWords:
                    text = "Correct.";
                    randomize();
                    break;
                default:
                    text = "Wrong.";
            }
            document.getElementById("comment").innerHTML = text
        }
    <input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
    <p id="randomWord"></p>
    <p id="comment"></p>



Aucun commentaire:

Enregistrer un commentaire