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>
Related
Trying to write a JS/HTML program that takes the user's name as an input and outputs "Hello, [Name]!" when you click he button.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
JS:
let txtName = document.querySelector('#txtName');
//let name = "lauren";
function sayHello() {
document.write("Hello, " + txtName + "!");
}
When I try to run it, it outputs "Hello, null!" everytime.
Move it to the function itself and add "value":
function sayHello() {
let txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}
Your function does not have access the the txtName variable. You should move it inside the function. You can also use getElementById instead of a query selector. Since were there, why not remove the variable entirely:
function sayHello() {
document.write("Hello, " + document.getElementById('txtName').value + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
Your code had 2 problems with it. One is scope and the other is value.
let txtName
As the variable is initiated using let, its scope is limited and not global. Use var to make it global, so it can get access inside functions too.
let txtName = document.querySelector('#txtName');
This line of code is running as soon as the page loads. So it is assigned the input object as the page gets loaded (and not the value). For printing the name, although we need the value of this object, (which is the second point) and not the whole object itself. We access its value by using .value.
var txtName = document.querySelector('#txtName').value;
Define this line inside the called function else it will get null value, because it will run as soon as the page loads and null value will be assigned because no input is there inside the input box.
function sayHello() {
var txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
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>
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>
Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.
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];