Chris Christensen
Chris Christensen

Reputation: 302

Comparing two functions in JavaScript

I'm developing a mobile app for my wife's 1st grade class so they can practice sight words. I'm a novice to JavaScript but I was able to pull off my first objective which was to take a JavaScript array and extract a random word from it. My second objective is to have the user type in the word that they see, click a button and have the word they entered be compared to the random word. I attempted to do this with a second function but it did not do it. I don't get any errors in the console so I'm a bit lost on how to get this working. Any help would be greatly appreciated by me and a great group of 1st graders. Here is the code that I have so far.

<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>

<input id="yourTurn">

<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>

<p id="result"></p>

<script>

var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;
var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";

function myFunction() {
    var showWord = sightWord[Math.floor((Math.random()*10)+1)];
    aWord.innerHTML = showWord;
}

function checkSpelling(result) {
    document.getElementById("result").innerHTML=checkWord;
}

</script>

</body>
</html>

Upvotes: 0

Views: 1224

Answers (6)

faino
faino

Reputation: 3224

There is a difference between innerHTML and value; the value is actually an attribute of the input tag. Here is a cross browser way to handle this, without any inline JavaScript:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <title>Practice Spelling Test</title>
        <meta charset="UTF-8" />
        <script>
            (function(d){
                var modern = (d.addEventListener) ? true : false, load = function(fn){
                    if(modern) {
                        d.addEventListener("DOMContentLoaded", fn, false);
                    } else {
                        d.attachEvent("onreadystatechange", function(){
                            if(d.readyState === "complete") {
                                fn();
                            }
                        });
                    }
                }, event = function(obj, evt, fn){
                    if(modern) {
                        obj.addEventListener(evt, fn, false);
                    } else {
                        obj.attachEvent("on" + evt, fn);
                    }
                }, init = function(){
                    var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"], newWordButton = d.getElementById("newWord"), checkSpellButton = d.getElementById("checkSpell"), aWord = d.getElementById("aWord"), yourTurn = d.getElementById("yourTurn"), result = d.getElementById("result"), lastWord = null, newWord = function(){
                        var count = Math.floor(Math.random()*(sightWord.length - 1));
                        if(count == lastWord) {
                            newWord();
                        } else {
                            aWord.innerHTML = sightWord[count];
                            lastWord = count;
                        }
                    }, checkSpell = function(){
                        var curr = aWord.innerHTML, input = yourTurn.value;
                        if(curr && input) {
                            result.innerHTML = (curr == input) ? "Nice Job!" : "So close! Try again!";
                        }
                    };
                    event(newWordButton, "click", newWord);
                    event(checkSpellButton, "click", checkSpell);
                };
                load(init);
            })(document);
        </script>
    </head>
    <body>
        <h1>Practice Spelling Test</h1>
        <p id="aWord">&nbsp;</p>
        <input id="yourTurn" type="text" />
        <button id="newWord">New Word</button>
        <button id="checkSpell">Check My Spelling</button>
        <p id="result"></p>
    </body>
</html>

Upvotes: 0

Alex Grande
Alex Grande

Reputation: 8027

Okay I got it working for you. I have it in a JS Fiddle: http://jsfiddle.net/D6ERg/4/

<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>

<input id="yourTurn">

<button onclick="window.wordApp.newWord()">New Word</button>
<button onclick="window.wordApp.checkSpelling()">Check My Spelling</button>

<p id="result"></p>

<script>

window.wordApp = (function() {
    var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
    var aWord = document.getElementById("aWord");

    return {
        newWord : function() {
            var showWord = sightWord[Math.floor((Math.random()*10)+1)];
            aWord.innerText = showWord;
        },
        checkSpelling : function() {
            var yourTurn = document.getElementById("yourTurn").value;
            var checkWord = (yourTurn == aWord.innerText)?"Nice Job!":"So close! Try again!";
            document.getElementById("result").innerHTML=checkWord;

        }
    }

})();
</script>

</body>
</html>

You had a lot of problems. Things that update need to be in functions. I also removed the global variables for best practices and easier debugging.

The (function() {})(); design pattern may be too advanced for you now, but you can look up closures or watch the video Paul Irish talking about how jQuery works. You will learn a lot. Also the book Javascript The Good Parts by Crockford is a book that I wish I read when I started.

Upvotes: 1

Joseph
Joseph

Reputation: 119847

This one avoids inline scripts:

HTML

<h1>Practice Spelling Test</h1>

<p id="aWord"></p>
<input id="yourWord">
<button id="newWord">New Word</button>
<button id="spellCheck">Check My Spelling</button>
<p id="result"></p>

JS

//list of words
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
//variable containing the current word
var currentWord;
//reference to the "congrats" box
var result = document.getElementById('result');
//reference to the input
var yourWord = document.getElementById('yourWord');

//when new word is clicked
document.getElementById('newWord').onclick = function () {
  //get a new word from the list
  aWord.innerHTML = currentWord = sightWord[Math.floor((Math.random() * 10) + 1)];
}

//when spell check is clicked
document.getElementById('spellCheck').onclick = function () {
  //compare and announce accordingly
  var check = (yourWord.value === currentWord) ? "Nice Job!" : "So close! Try again!";
  result.innerHTML = check;
}

Upvotes: 0

Mohsen
Mohsen

Reputation: 65795

You mixed up value and innerHTML.

value is used for input and textarea elements and innerHTML is for almost other element

This code will work for you:

<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>

<input id="yourTurn">

<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>

<p id="result"></p>

<script>

var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn");
var aWord = document.getElementById("aWord");


function myFunction() {
    var showWord = sightWord[Math.floor((Math.random()*10)+1)];
    aWord.innerHTML = showWord;
}

function checkSpelling(result) {

  var checkWord = (yourTurn.value == aWord.innerHTML)?"Nice Job!":"So close! Try again!";
    document.getElementById("result").innerHTML=checkWord;
}

</script>

</body>
</html>

See live code here: http://jsbin.com/ubofus/1/edit

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Cleaned up your code a little, also fiddled: http://jsfiddle.net/3Ptzu/

var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];

var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;


function myFunction() {
   var showWord = sightWord[Math.floor((Math.random()*10)+1)];
   document.getElementById("aWord").innerHTML = showWord;
}

function checkSpelling(result) {
    var challengeWord = document.getElementById("aWord").innerHTML;
    var checkWord = document.getElementById("yourTurn").value;

    var result = (challengeWord == checkWord) ? "Nice Job!":"So close! Try again!";
    document.getElementById("result").innerHTML = result;
}

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60767

The problem is that you're evaluating checkWord only once, when the browser runs your JavaScript.

So, the checkWord variable is always "Nice Job!".

Another problem is that you're using value on a p element. p elements don't have such properties.

And the last issue is that you're comparing 2 values with ==. It isn't enough, because "" == undefined, undefined being what value on a p element returns.

To sum it up, you want to evaluate checkWord every time, and you want to compare apples to apples. Which would lead to this kind of code:

function checkSpelling(result) {
    var yourTurn = document.getElementById("yourTurn").value;
    var aWord = document.getElementById("aWord").innerHTML;
    var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";
    document.getElementById("result").innerHTML=checkWord;
}

One last thing: I'm using innerHTML there, but it's bad. You don't want HTML, you want text. It'd be better to use textContent, or innerText on older IE (6, 7, 8). If you don't want to worry about this kind of cross-browser mess, use a library to abstract away all of this.

Upvotes: 1

Related Questions