1

When I click the button

<button onclick="game();">Submit</button>

it says in the console "Uncaught ReferenceError: game is not defined". I defined it in the script as

function game(){};

And called it in the head with

<script src="numbers.js" type="text/javascript"></script>

Shouldn't it run?

  • Did you make sure your script gets loaded properly? Watch the browser's network tab on the developer tools. You should see it request the JavaScript file and there shouldn't be an error code there. – mason Nov 28 '15 at 22:44
  • Is number.js in the same directory on the same level as the HTML file? – Ravenous Nov 29 '15 at 00:58
  • It is loading and in the same directory. – redfacedone Nov 29 '15 at 02:02
  • Perhaps numbers.js is cached in your browser. Try browsing to numbers.js and check the contents are what you expect. Clear the cache if it is different. – Jeremy Larter Nov 29 '15 at 03:41
  • Yes, it should run and does for me locally. If there is any extra JavaScript in `numbers.js` or other scripts loaded, could you please link a [fiddle](https://jsfiddle.net/)? – Jeremy Larter Nov 29 '15 at 03:59
  • @JeremyLarter The contents are what I expect, and [here](https://jsfiddle.net/yrcba1Lh/) is the fiddle. – redfacedone Nov 29 '15 at 20:09
  • Thanks. There are some syntax errors in your `game()` function such as missing closing curly braces and `elseif` should be `else if`. I could post corrected code, but you would get more out of using http://www.jslint.com/ and console output using `console.log()` to check what you expect. Let me know if you are still having trouble. – Jeremy Larter Nov 29 '15 at 20:51

1 Answers1

2


You have some errors in your javascript.
There is no elseif keyword in javascript.

Secondly, we have some problem with bracket orders.

Here you have a working version:

function game() {
    var number = document.getElementById("myNumber").value;
    var number = Number(number);
    stepnumber.push(number);
    var orignumber = number;
    if (number !== "NaN") {
        for (step = 0; step > 1; step + 0) {
            if (number % 2 === 0) {
                number = number / 2;
                stepnumbers.push(number);
                step += 1;
            }
            else if(number % 2 === 1) {
                number = number * 3;
                number += 1;
                stepnumbers.push(number);
                step += 1;
            }

            document.getElementById("output").innerHTML = "Your number, " + orignumber + " took " +
            step + " steps to reach 1, the numbers it went through (in order) were: "
            + stepnumbers.toString() + ". Thanks for using this random 'tool'!";
        }
    }
    else {
        document.getElementById("output").innerHTML = "You didn't type in a number, try again."
    };
}
Ygalbel
  • 5,214
  • 1
  • 24
  • 32