If the value of an input is stored in a variable and the variable is declared in outside a function (global) and the value stored in variable retrieved from the function , it gives either give undefined or empty string BUT if variable is declared inside the function if works as intended
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script>
var a = document.getElementById("txt").value;
function dis(){
console.log(a);
}
</script>
</head>
<body>
<input type="text" id="txt">
<button onclick="dis()">Click</button>
</body>
</html>
The problem you seem to encounter is not one of scope but of timing: When you declare your variable a the input is still empty. So the result you get shown will also be empty. No matter what current contents the input field might hold at the time.
The following, modified, version should achieve what you wanted:
var a = document.getElementById("txt")
function dis(){
console.log(a.value);
}
<input type="text" id="txt">
<button onclick="dis()">Click</button>
you should update a every time dis called:
and make sure dom content is loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
var a = document.getElementById("txt").value;
});
function dis(){
a = document.getElementById("txt").value;
console.log(a);
}
</script>
</head>
<body>
<input type="text" id="txt">
<button onclick="dis()">Click</button>
</body>
</html>
Related
I was getting this error in my console while trying to execute a function using the "onclick" event inside of a button. The error I got was,
Uncaught ReferenceError: foo is not defined
onclick http://localhost:3001/bar:1
onclick http://localhost:3001/bar:1
I defined foo like this in the <body> tag followed by a script tag,
function foo(){
fooBar();
}
Thanks.
Edit: Heres my code.
<!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">
<meta name="description" content="app lol">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title><% title %></title>
</head>
<body>
<script>
function foo() {
fooBar();
}
</script>
<button onclick="foo()">bar</button>
</body>
</html>
<!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"> <meta name="description" content="app lol"> <script src="unpkg.com/axios/dist/axios.min.js">
</script>
<title></title>
</head>
<body>
<script>
function fooBar()
{
alert("hey");
}
function foo()
{
fooBar();
}
</script>
<button onclick="foo()">bar</button>
</body>
</html>
<html>
<head><title></title></head>
<body>
<button id="btn" onClick="foo()">Click me </button>
<script>
btn = document.getElementById("btn");
function foo(){
btn.style.color = "red";
}
</script>
</body>
</html>
This works!
Add an ID to your button. onclick is kinda buggy, because Google security features prevent you from doing so. It is even a good idea to separate JavaScript and HTML.
I usually assign an ID to a div, and querySelector them.
<div id="an-id">
<input />
</div>
document.querySelector("#an-id").querySelector("input").addEventListener("click", foo);
(Put your script after the button)
Is this how your setup looks? If yes, there shouldn't be any error.
<script>
function foo () {
console.log('Foo function');
}
</script>
<button onclick="foo()"> My Button </button>
[I don't why I am getting this error, My JS code is running fine directly in the console of my browser but when I am trying to attach a .js file to my html I get this error.[][1]1
://i.stack.imgur.com/wON7T.jpg
var button1 = document.querySelector("button");
var isPurple = false;
button1.addEventListener("click", function(){
if(isPurple){
document.body.style.background = "white";
isPurple = false;
} else {
document.body.style.background = "purple";
isPurple = true;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="MyTitle.js"></script>
</head>
<body>
<button>click me</button>
</body>
</html>
tHe code supplied seems to work fine - as noted int the comments - where you place the external js - make sa difference - it should be placed at the end of the code - just before the closing body tag. As a rule - place all the external CSS files in the head and all external js files in the body - unless there is some rendering based logic that is required in the javascript.
In this case - the javascript is intended to identify the button using the querySelector() - but it is not in the DOM yet so cannot be identified.
Also - you can simplify your code and just toggle the variable on the click and then use a ternary for adding / romoving a class with the background color set to the class. Its always better to use classes with styling attached rather than amendifing the CSS via the javascript.
var button1 = document.querySelector("button");
var isPurple = false;
button1.addEventListener("click", function(){
isPurple = !isPurple;
isPurple
? document.body.classList.add('purple')
: document.body.classList.remove('purple')
});
.purple {
background: purple;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script>
</body>
</html>
Of course - you could actually remove the variable totally - its always better if you can move away from global variables when possible - the following simply toggles the class on the button click.
var button1 = document.querySelector("button");
button1.addEventListener("click", function(){
document.body.classList.toggle('purple')
});
.purple {
background: purple;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="MyTitle.js"></script>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script>
</body>
</html>
The problem is that at the time the JavaScript is run the button element does not yet exist in the DOM. Load it afterwards and it should then exist OK.
In general it is wise to load such JS, i.e. that is going to run immediately on load, at the end OR put it into a window.onload function (especially if the code relies on images being already loaded).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script> </body>
</html>
I am trying to create a magic 8 ball. I've added the answers at the top in an array, added the code to choose a random answer, and when the button is clicked, it's supposed to place said random answer in a p tag in a div. It actually worked very well a few times in codePen and then stopped. I didn't change a thing. Can anyone tell me what I'm missing if anything?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
</body>
</html>
JavaScript
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
function myFunction(){
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
I've tried moving things around and looking addEventListener up. There's a few questions here on that, too, but I haven't found anything that solves my issue.
Try reordering the placement of your <script> tag in you HTML , so that the script is run after the DOM is loaded/parsed.
When your script is run, the button that you're trying to add a click listener to is not going to be present because the script is run from the <head> tag before the <body> DOM contents are loaded and ready.
Try the following adjustment:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
<!-- Put script here instead -->
<script src="script.js"></script>
</body>
</html>
Also, consider revising your javascript so the the randomAnswer is recomputed each time the user clicks the button, so that the answer shown to the answer is able to change per button click:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
function myFunction(){
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
Your script is loaded in the header. It's executed whereas the page didnt finished to load, so you're trying to attach a listener to the button element that doesnt exist yet. Move it to the bottom of the body section:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
// deleted
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
<script src="script.js"></script> // pasted here
</body>
</html>
The problem is that your randomAnswer needs to be defined inside of the function, so that the answer gets decided upon each time you press the button. Outside of the function it gets defined on page load, and the answer will be the same each time.
Here's an updated snippet:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"
];
function myFunction() {
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
</body>
</html>
Move
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
inside of your function like this:
function myFunction(){
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction=()=>{
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
});
Place the logic inside the function and it will be created everytime that it is called.
Or ou could assign the function to a variable like this:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
let myFunction = function(){
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
I started to work on a clicker game in JavaScript, but it's not working. I used the console to inspect the element to find out why it won't add anything to money and I don't think it is showing the variable either because it won't even show a 0.
<!doctype html>
<html lang="en">
<head>
<script>
function addMoney() {
var money
money+1;
var cash = document.getElementById("showmoney");
cash.innerHTML=money;
}
</script>
<meta charset="utf-8">
<title>clicker game</title>
</head>
<p id="showmoney"></p>
<body>
<button id="click" onClick="addMoney">click</button>
</body>
</html>
The call to the function should have parenthesis () :
<button id="click" onClick="addMoney()">
Instead of :
<button id="click" onClick="addMoney">
Also you have to init you variable money and to define it in the global scope so it will not return to default value zero on every click :
var money=0;
Hope this helps.
<!doctype html>
<html lang="en">
<head>
<script>
var money=0;
function addMoney(){
money++;
var cash = document.getElementById("showmoney");
cash.innerHTML=money;
}
</script>
<meta charset="utf-8">
<title>clicker game</title>
</head>
<p id="showmoney">
</p>
<body>
<button id="click" onClick="addMoney()">
click
</button>
</body>
</html>
This question already has answers here:
JavaScript get TextArea input via .value or .innerHTML?
(5 answers)
Closed 7 years ago.
< script type = "text/javascript" >
function myFunction() {
var n1 = document.getElementById("form-control1").innerHTML;
var n2 = document.getElementById("form-control2").innerHTML;
return Math.max(n1, n2);
};
<!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">
<title>JavaScript Challenge</title>
</head>
<body>
<!-- user interface -->
First number
<input type="text" id="form-control1" placeholder="your first number">Second number
<input type="text" id="form-control2" placeholder="your second number">
<br>
<br>
<button onclick="myFunction()">Calculate</button>
</script>
</body>
</html>
I would like the user input value to be assigned on the variable n1 and n2. After that when the button is clicked the variable with the max value is shown up on the webpage. but at the moment the value does not seem to be stored as it says undefined.
what can i do? any help
Thanks in advance
Try substituting .value for .innerHTML at input elements to retrieve value of input element; create array containing n1, n2 , converting to values to Number using Array.prototype.map() , adding output element to print result of Math.max to document
<!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">
<title>JavaScript Challenge</title>
</head>
<body>
<!-- user interface -->
First number
<input type="text" id="form-control1" placeholder="your first number">Second number
<input type="text" id="form-control2" placeholder="your second number">
<output></output>
<br>
<br>
<button onclick="myFunction()">Calculate</button>
<script type="text/javascript">
function myFunction() {
var n1 = document.getElementById("form-control1").value;
var n2 = document.getElementById("form-control2").value;
document.querySelector("output").innerHTML = Math.max.apply(Math, [n1, n2]);
};
</script>
</body>
</html>
Convert the innerHTML string into an integer:
return Math.max(parseInt(n1),parseInt(n2));