I am a very new programmer that was challenged to make a bitcoin clicking game. I am about ten percent done and have spent hours trying to debug my site. I get this error. Uncaught ReferenceError: add is not defined
at HTMLAnchorElement.onclick It all worked perfectly fine until I added a upgrade function. After that it did not work. Not even deleted it made a difference.
<script>
function update() {
document.getElementById('text').value = bitcoincount;
document.title = bitcoincount + " Bitcoin";
document.getElementById('amountithree').innerHTML = "You Own " + ithree + " i3's";
}
var bitcoincount = 0;
var ithree = 0;
function timer() {
bitcoincount = bitcoincount + ithree;
update()
}
setInterval(timer, 1000)
</script>
<html>
<head><title>Bitcoin</title></head>
<body>
<img src="opengraph.png" height="200" width="200">
<br><br>
You got:
<input type="text" id="text" disabled style=text-align:center>
<script>
function add() {
bitcoincount = bitcoincount + 1
document.getElementById('text').value
bitcoincount;
document.title = bitcoincount + " Bitcoin";
}
</script>
Bitcoin.
<br><br>
<button>Save</button>
<button>Load</button>
<br><br>
<p>Buy 1 i3 6100</p>
<button><img src=ithree.jpg width="100" height="100"></button>
<p id="costithree"> Bitcoin</p>
<p id="amountithree">You Own 0 i3's</p>
<script>
function save() {
localStorage.setItem("bitcoincount", bitcoincount);
}
function load() {
bitcoincount = localStorage.getItem("bitcoincount");
bitcoincount = parseInt(bitcoincount);
update()
}
function buyithree() {
if (bitcoincount >= ((ithree + 1) ^ 12)) {
bitcoincount = bitcoincount - ((ithree + 1) ^ 12);
update()
}
}
</script>
</body>
</html>
I don't know if this will fix your problem, but I'd move the first <script...>...</script> block to be inside the <html>...</html> block, preferably inside <head>...</head>.
you have a typo in your add() function, that's why the browser can't recognize it
document.getElementById('text').value bitcoincount;
should be :
document.getElementById('text').value = bitcoincount;
Your function have error thats why its not created Please ckeck console for errors
Change this add assignment operator
document.getElementById('text').value = bitcoincount;
Related
I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.
I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).
<!DOCTYPE html>
<html>
<body>
<button class="button" onclick="disp()">Generate</button>
<button class="button" onclick="show_ans()">Show</button>
<script>
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
var j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
}
</script>
<p> Random Integer:
<span id="Goal"></span>
</p>
<p> Computed Answer:
<span id="answer"></span>
</p>
</body>
</html>
show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.
Move it outside that function:
function disp() {
//...
}
function show_ans() {
//...
}
Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:
var j;
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
This is code I've written for a class assignment. The assignment reads as follows:
"Build a function that will start the program. Please call it main().
From the main() function, call a function called getValue().
The getValue() function will get a number from the user that will be used for the next step.
Also from the main() function, call a function called getSquareRoot().
The getSquareRoot() function will get the square root of the number that was received by the user in the getValue() function.
Make sure that you display the results, including the original number and the square root of the number, to the user in an easily readable statement.
Bolding is included in the original, by the way.
Here's my code and it works, except that somehow functions are being called twice, and results are being displayed twice, with the second iteration assigning userInput a value of 0. I can't seem to identify where the 'loop' is getting fired off (beginner here). Any help would be very much appreciated; I know I'n staring at it but it's totally eluding me.
<html lang="en">
<head>
<title>Project 3 Part A</title>
<meta charset="utf-8">
<script>
function main()
{
var msg1="";
var msg2="";
var userInput = "";
getValue(userInput);
getSquareRoot(userInput);
}
function getValue(userInput)
{
var userInput = document.getElementById("userNumber").value;
return getSquareRoot(userInput);
}
function getSquareRoot(userInput)
{
squareRoot = Math.sqrt(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
</script>
</head>
<body>
<br>
<input type="button" id="userInputButton" onclick="javascript:main();" value="Square root input value: "/>
<input type="text" id="userNumber">
</div>
<div id="original">
</div>
<div id="results">
</div>
</body>
enter code here
You need to remember that each function should optimally have 1 purpose only. The function 'getSquaredRoot' here is in charge of both calculating the root as well as outputting the result for the user to see.
Plus as Lucky Chingi said, you're calling getSquaredRoot twice.
function main()
{
var userInput = getValue();
var squaredRoot = getSquareRoot(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
function getValue()
{
return document.getElementById("userNumber").value;
}
function getSquareRoot(userInput)
{
return Math.sqrt(userInput);
}
Notice how it's logically seperated now.
Error: Uncaught ReferenceError: myFunction is not defined
This is my .js file which isn't working or calling on my HTML
function = myFunction()
{
var ret = "";
for (var i = 15; i < 26; i++)
{
ret += i + " " + i*2 + " " + i*3 + "\n";
}
alert(ret);
}
This is my HTML code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="Test1.js"></script>
</head>
<body>
<h1> Exercise 4 - LAB 4 </h1>
<h2> Exercise 2.1 </h2>
<button type="button" onclick= "myFunction() "> Press Me </button>
</body>
</html>
Error: Uncaught ReferenceError: myFunction is not defined
Here you go:
var myFunction = function ()
{
var ret = "";
for (var i = 15; i < 26; i++)
{
ret += i + " " + i*2 + " " + i*3 + "\n";
}
alert(ret);
};
function = varName () {} is a syntax error. You can do it like this: function varName () {} without the equals sign, or you can do it the way I did it.
After a little bit of healthy admonishment from some of our fellow posters, I should point out that there is a difference between these two ways to write a function. To quote RobG: "There is no practical difference between function foo(){} and var foo = function(){}; other than when the function is created and that the first is called a FunctionDeclaration and the second a FunctionExpression." A function declaration is loaded before any code is executed, so you can can call it anywhere (before or after the function's location in the file). However, again in terms of actual location in the file, if you call a function expression before its location in the file, an error will be thrown. (You can however get around this by declaring the variable that will later be assigned to the function expression at the beginning of the file.)
function = myFunction() { /* body */ }
is invalid syntax. Didn't you get an error in the console from this? The correct syntax is either
function myFunction() { /* body */ }
or
myFunction = function() { /* body */ }
You can also write:
somename = function myFunction() { /* body */ };
However, in this case the scope of the name myFunction is just the body, it's not global.
The declaration of the function is wrong:
Javascript:
function myFunction() {
var ret = "";
for (var i=15; i<26; i++) {
ret += i + " " + (i*2) + " " + (i*3) + "\n";
}
alert(ret);
}
HTML
<html>
<head>
<script type="text/javascript" src="Test1.js"></script>
</head>
<body>
<h1>Exercise 4 - LAB 4</h1>
<h2>Exercise 2.1</h2>
<input type="button" value="Press Me" onclick="myFunction()" />
</body>
</html>
I have two arrays sd[16][16] and gd[16][16] in javascript. I need to compare the values of the arrays.
var score=0;
document.write("<table>");
for(c1=0; c1<16; c1++)
{ document.write("<tr>");
for(c2=0; c2<16; c2++)
document.write("<td onClick='changeColor(this);'>" + gd[c1][c2] + "</td>");
document.write("</tr>");
}
document.write("</table>");
function changeColor(tdd)
{
if(tdd.bgColor=='white')
{
tdd.bgColor='red';
if (gd[c1][c2] == sd[c1][c2])
score+=5;
else
score-=2;
}
else
{
tdd.bgColor='white';
}
}
However, when I try to display the score later, the score is not displayed.
function scc()
{
document.getElementById('scf').innerHTML = score;
}
</script>
<br><br><center><button type='button' onclick='scc()'> Click to see current score</button> <p id="scf">0</p> </center>
<br><br> <center><input type="submit" value="Get Solution"/></center>
Could someone please tell me what I am doing wrong?
It's a little more work but you could use a closure to keep the score variable isolated.
var score = (function () {
var currentScore = 0;
return {
getScore: function() { return currentScore; },
updateScore: function(change) { currentScore += change; }
}
})()
and then you can get/set the score like this: score.getScore(); and score.updateScore(5); score.updateScore(-4)
This way you don't have to worry about stepping on your score accidentally.
You have forgotten to initialize the score-variable. Now you have the problem your score is only available in the changeColor-function. You can define a score-variable outside all the functions, so that it's available everywhere:
<script type="text/javascript">
var score = 0;
document.write ...
</script>