NaN error - Dealing with strings and integers - javascript

Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.

It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>

Related

Basic JavaScript how to call a function from the HTML page

I have just started JavaScript basics and I'm struggling with this:
HTML page has the following:
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
This page should call the function calcSquare(), which fetches the value of the element, calculate its square, and print in the console: The square of 5 is 25. The HTML page loads the code, so I can refer to the page with the document keyword. My js code is following:
function calcSquare() {
var number = document.getElementById("number").value;
console.log("The square of" + number + "is" number*number);
}
Can someone tell me what is wrong with it? Thank you so much! Beginners struggles...
The problem is with your function itself.
Keep in mind that .value is used with an input element. So you can use .innerHTML or .textContent.
You forgot also the sign + after "is".
Look at this code snippet .
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
<script>
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
</script>
</body>
</html>
Instead of .value use .innerHTML, and you are missing sign + after "is"
You need to get textContent, and make some changes in your function calcSquare()
function calcSquare() {
var number = document.getElementById("number");
var number = number.textContent;
console.log("The square of" , number , "is" , number*number);
}
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
And if you are use an input-field you make it more dynmaic :) and if the is target an input you can use the .value
Be sure you cast every time your vars into the right type before do math (parseInt, parseFloat etc)
And because you are new on JS please deal with JS Security - it is very important for your future dev..
https://snyk.io/learn/javascript-security/
https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
Try this . Foe elements such as P or Div You have to ue textContent or innerHTML to get the data inside the tag. You missed string concatenation after "is" too
function calcSquare() {
var number = document.getElementById("number").textContent;
console.log("The square of" + number + "is" +number*number);
}
<body>
<p id="number">6</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
<script>

redundant command line of javascript program?

I am newbie with javascript and I wrote a very simple program to display something using function and alert. Here is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var balance = 10500;
var cameraOn = true;
function steal(balance, amount){
cameraOn = false;
if (amount < balance) {
balance = balance - amount;
}
return amount;
cameraOn = true;
}
var amount = steal(balance, 1250);
alert("Criminal: you stole " + amount + "!");
</script>
</body>
</html>
The code is ok, when I ran it, it display "Criminal: you stole 1250!" as I expected. But, my problem is, in my code as you can see, there is a code cameraOn = true; I do not know why I must write this code ( I copy this code from the book I studied ).
When I made this line to be referenced, the result did not change. So, I thought that this code is not necessary ?
Could you please give me some ideas for me with this problem ? Thank you very much.
It's not executed since it's written after the "return" keyword.
So yes, you can (you should) delete this line.

Can't figure out how to randomly generate numbers with a button in javascript

followed a tutorial just with different layout and names and still can't seem to find whats wrong?
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = math.floor((math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
Reason :
What you are doing wrong is that you are using math instead of Math. JavaScript is case sensitive and Math is defined while math is not.
Corrected :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
<script>
var myrandom = () => {
var x = ~~((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</body>
</html>
Also please note that it is better that you write the JS code at the end of the body tag and the script tag is the last one in the body tag.
Note :
Note that I edited the snippet provided by you.
The following edits were made
The script tag was moved at the end of body tag
I changed the function and used arrow syntax instead of normal declaration
Changed Math.floor into bitwise ~~
Resources :
Stack overflow script tag
W3 schools script tag
bit wise operators mozilla
bit wise operators W3 schools
Arrow function mozilla
You have a typo, You need to capitalize the first letter of math -> Math.
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>

function write(message) not working

I'm doing the PluralSight JavaScript Fundamentals course and he enters this code into the JavaScript window of jsbin (jsbin.com)
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick";
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
and when he Previews it writes out the types and values. The video is a year old and now jsbin has a Render (not Preview) button. When I enter the above code and Render I get a blank screen.
I tried pasting the code into an .html file
<!DOCTYPE html>
<html>
<head>
<!--<meta charset=utf-8 />-->
<title>JS Test</title>
</head>
<body>
<p id="hello">Hello World</p>
<script>
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick"';
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
</script>
</body>
</html>
and then opened the file in IE9, and the latest version of Chrome, Firefox, Safari and Opera (my OS is Win7 Ult). They all display Hello World and nothing else. I'm probably missing something really simple here, can someone help me out?
You don't have a message element. Change the #hello element to #message.
<p id="hello">Hello World</p>
To this
<p id="message">Hello World</p>
This is what is needed for the getElementById code to have a place to print your output. Without an element having the requested ID, nothing will turn up, and hence nothing will be printed.
You have a syntax error as well:
/* v----- This little guy here doesn't belong. */
var streetName = "Brunswick"';
Note the umatched single quote at the end of this string. Remove that and you should be good to go:

Returning currently displayed index of an array Javascript

I have a simple array with x number of items. I am displaying them individually via a link click... I want to update a number that say 1 of 10. when the next one is displayed i want it to display 2 of 10 etc...
I have looked all around and my brain is fried right now... I know its simple I just cant get it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Title</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/>
<script type="text/javascript">
var quotations = new Array()
quotations[0]= "abcd"
quotations[1]= "efgh"
quotations[2]= "ijkl"
quotations[3]= "mnop"
quotations[4]= "qrst"
quotations[5]= "uvwx"
quotations[6]= "yzab"
numQuotes = quotations.length;
curQuote = 1;
function move( xflip ) {
curQuote = curQuote + xflip;
if (curQuote > numQuotes)
{ curQuote = 1 ; }
if (curQuote == 0)
{ curQuote = numQuotes ; }
document.getElementById('quotation').innerHTML=quotations[curQuote - 1];
}
var curPage = curQuote
</script>
</head>
<body>
<div id="quotation">
<script type="text/javascript">document.write(quotations[0]);</script>
</div>
<div>
<p>GO back
<script type="text/javascript">document.write(curPage + " of " + numQuotes)</script>
GO FORTH</p>
</div>
</body>
</html>
Edit: curQuote is not updating dynamically... it stays at '1' when next is clicked.
In your code, curQuote is already the value you want. I rewrote everything to clean it up and show some better logic/syntax. Note that ideally you would be attaching the click handlers via DOM methods and not using inline handlers, but for simplicity I've left it that way here.
Working version viewable here: http://jsbin.com/irihu3/2
<html>
<head>
<title>Quotations</title>
<script type="text/javascript" charset="utf-8">
var quotations = ["hi", "how", "are", "you", "today", "good", "sir"],
lastIndex = quotations.length - 1,
currentIndex = 0;
function move(xflip) {
currentIndex = currentIndex + xflip;
if (currentIndex > lastIndex) {
currentIndex = 0;
} else if (currentIndex < 0) {
currentIndex = lastIndex;
}
document.getElementById('quotation').innerHTML = quotations[currentIndex] + " (Quote #" + (currentIndex + 1) + ")";
return false;
}
</script>
</head>
<body>
<div id="quotation">hi (Quote #1)</div>
<a onclick="move(-1);">Prev</a>
<a onclick="move(1)">Next</a>
</body>
</html>
Some things to note:
Always declare variables with the var keyword or you create global variables.
You can combine multiple variable declarations into one statement by separating them with commas. It's good practice to stick to one var statement and to put it at the top of your code/function.
All you really need to keep track of here is the current index of the array, not the quote itself. It's also not important how long the array is, just what the last index is. As such, in my code I am using currentIndex and lastIndex instead of curQuote and numQuotes.
Using return false; at the end of your function will suppress the default action when clicking on a hyperlink (not following the link). This is what you want in this case, because you're using a hyperlink to trigger behavior on the page and not actually navigating to another page.
You're making a lot of beginner mistakes in your JavaScript but it seems as if curQuote has the value you want, no?
Tips:
You can declare an array as such: var array = [1,2,3,4,5,6,7];
Terminate statements with a semi-colon.
Use var keyword for local variables.
Don't put braces around one line if statements bodies.
Use indentation properly to make the code readable.
Try this
var curPage = quotations[curQuote];

Categories

Resources