How do I make variables change outside functions in javascript? - javascript

I am a beginner with Javascript/programming and I am trying to make the "demo2" id change with the 5, 10 or 15 variable chosen in the functions (trigger by the buttons), but it keeps showing "0". What do I have to do?
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative1()">5</button>
<button onclick="alternative2()">10</button>
<button onclick="alternative3()">15</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
var x = 0;
var y = 0;
function alternative1() {y = x + 5;
document.getElementById("demo").innerHTML = "You have chosen " + y;
}
function alternative2() {y = x + 10;
document.getElementById("demo").innerHTML = "You have chosen "+ y;
}
function alternative3() {y = x + 15;
document.getElementById("demo").innerHTML = "You have chosen "+ y;
}
document.getElementById("demo2").innerHTML = y;
</script>
</body>
</html>

You can’t access variables declared inside a function from outside a function. The variable belongs to the function’s scope only, not the global scope.

It is normal that there is zero because in 'y' there is zero and no operation performed on y.
I hope that this answer will help you to understand what you have done.

You don't need 3 functions for this. You can do it with 1.
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative(this)">5</button>
<button onclick="alternative(this)">10</button>
<button onclick="alternative(this)">15</button>
<p id="demo"></p>
<script>
function alternative(obj) {
document.getElementById("demo").innerHTML = "You have chosen " + obj.innerHTML;
}
</script>
</body>
</html>
Happy learning

You need to change 'demo2 inner' after every operation and need to add new value to 'y' current value (use +=)
var x = 0;
var y = 0;
function alternative(param) {
y += x + param;
document.getElementById("demo").innerHTML="You have chosen "+ param;
document.getElementById("demo2").innerHTML = y;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative(5)">5</button>
<button onclick="alternative(10)">10</button>
<button onclick="alternative(15)">15</button>
<p id="demo"></p>
<p id="demo2"></p>
</body>
</html>

Related

javascript getElementById outside function does not work

I am relatively new to javascript and made this simple guess the number program. My question is this:
Why does it only work if:
var myNumber = document.getElementById("myNumber").value;
is defined within the function. I thought that if it was defined outside the function it will have "scope to b used within it?
Thank you for any help.
<p> Enter your number 1-10 <input id="myNumber" type="text"> </p>
<button id="btn1">Go</button>
<script type="text/javascript">
document.getElementById("btn1").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var number = parseInt(myNumber);
var count = 1;
var computerGuess = Math.floor((Math.random() * 10) + 1);
while (computerGuess !== number) {
computerGuess = Math.floor((Math.random() * 10) + 1);
count++;
}
alert("you guessed it" + " in " + count + " guesses");
}
</script>
When you will use document.getElementById in global scope it will return undefined if
the script is above the element which you wanna access. Because it can get element by id before it is created
Solution 1. Use all your script tags at last of all elements
Solution 2. use this way
<!DOCTYPE html>
<html>
<body>
<script>
var globalElm;
function start(){
globalElm = document.getElementById('elm')
}
setTimeout(start,50);
</script>
<div id="elm"></div>
</body>
</html>

Count to 100 using Javascript (in a div) [duplicate]

This question already has answers here:
using innerHTML in a loop is not properly displaying the set of json results
(4 answers)
Closed 5 years ago.
I wanne count to 100 in a div only using javascript. Why does only comes the last number.
Here is my code:
function test() {
for (var x = 1; x < 101; x++) {
document.getElementById("demo").innerHTML = (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
change document.getElementById("demo").innerHTML += (x + "<br />"); this line
function test() {
for (var x = 1; x < 101; x++) {
document.getElementById("demo").innerHTML += (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
Because the keep overriding the contents of the div with id "demo" by using innerHTML. You need to append the new number.
Please see this example (I updated your code).
function test() {
for (var x = 1; x < 101; x++) {
var current_contents = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = current_contents + (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
Because it happens so fast that you only see the last number. Do something like this:
var _counter = 1;
var _timer = null;
function test() {
_counter = 1;
_timer = setInterval(function(){
document.getElementById("demo").innerHTML = (_counter + "<br />");
_counter++;
if(_counter > 100) clearInterval(_timer);
}, 1000);
}
function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<div id="demo"></div>
<button onclick="test();">Count</button>
<button onclick="leer();">Delete</button>
Try using .append instead of .innerHTML

how to use a global variable inside a function in javascript?

I want to use global variables 'x, y' in the below funcion.
it works when I put the variables inside the function
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var x = document.getElementById('field_one').value
var y = document.getElementById('field_two').value
function calculator()
{
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" value="multiply them!" onclick="javascript:calculator()"/>
</form>
</body>
</html>
Your code works. But youre running in a race problem. You try to find Elements, before they are created:
var x, y;
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
}
If your site is loading for a long time, the user may try to start the calculator script before x and y are set. Solution:
var x, y, calculator;
calculator = function() {
alert("please wait, until the site is completely loaded");
};
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
calculator = function() {
alert(x + " times " + y + " is " + x * y);
};
}
The problem is as you want to get the value of x and y but them doesn't are setted value when function is called. If you want to use the variables many times, you need the create a function (I called setValues) that is responsible the set the value of x and y with the value of input, and always you need to get the values of input you can call it. Something like this:
var x;
var y;
function setValues() {
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
}
document.getElementById("calc").addEventListener("click", function() {
setValues();
var p = x * y;
alert(x + " times " + y + " is " + p);
}, false);
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" id="calc" value="multiply them!" />
</form>
Positioning your script after the .html content guarantees everything is defined at the time you want the script working.
You can declare global variables from a local scope simply not using 'var' on declaration.
Do not forget to end each statement with a ';'
This way, your code is 100% functional:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" id="field_one"/> <br/>
Number 2: <input type="text" id="field_two"/> <br/>
<input type="button" value="multiply them!" onclick="readFields();"/>
<script type="text/javascript">
function readFields(){
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
calculator();
}
function calculator(){
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</form>
</body>
</html>

how to store variable`s name in another variable

i`m working on school project
how can i access the name of variable and store it to in another variable ex: y[i].
what to write in place of comment below in javascript code.
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
Here is what you search for : You have to construct a object with your arrays and pass trow all the arrays.
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
Since you ask for what i was talking about. I'll give you the code.
Again, to re-iterate my point, you cannot get the variable name. But if you must have the variable somehow, you can work around by putting all the variables you need access to in an object.
you will not get the variable name of the object, but you can access all the properties names of this object.
Here is the codepen link to see the code running.
html
<p id="test"><p>
js
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}

How do I change the value of a global variable from function?

What is the problem here when I click the buttons that are supposed to change the value?
<html>
<head>
<script type="text/javascript">
var x = 45;
var j = " I love pancakes";
</script>
</head>
<body>
<button type="button" onclick="f1();">Click me to change number</button>
<button type="button" onclick="f2();">Click me to change sentence</button>
<center>
<script type="text/javascript">
function f1()
{
if (x == 45)
{
x = 32;
}
}
function f2()
{
if (j == " I like pancakes")
{
j = " I don't like pancakes";
}
}
document.write(x);
document.write(j);
</script>
</center>
</body>
</html>
You can change the value of these variables just the way you've done it. However, the document.write won't be re-run automatically. The text you see on the page won't change, even though the variables have been updated.
Try using DOM to modify the content of the page when your event handler runs.
<html>
<head>
<script type="text/javascript">
var x = 45;
var j = " I love pancakes";
</script>
</head>
<body>
<button type="button" onclick="f1();">Click me to change number</button>
<button type="button" onclick="f2();">Click me to change sentence</button>
<center>
<script type="text/javascript">
function update()
{
document.getElementById('output').innerHTML = x + j;
}
function f1()
{
if (x == 45)
{
x = 32;
}
update();
}
function f2()
{
if (j == " I like pancakes")
{
j = " I don't like pancakes";
}
update();
}
document.write('<span id="output">');
document.write(x);
document.write(j);
document.write('</span>');
</script>
</center>
</body>
</html>
Try this:
<html>
<head>
<script type="text/javascript">
var x = 45;
var j = " I love pancakes";
</script>
</head>
<body>
<button type="button" onclick="f1()">Click me to change number</button>
<button type="button" onclick="f2()">Click me to change sentence</button>
<p id="sentence"></p>
<center>
<script type="text/javascript">
document.getElementById("sentence").innerHTML=x+j;
function f1(){
if (x == 45){
x = 32;
} else {
x = 45;
}
document.getElementById("sentence").innerHTML=x+j;
}
function f2(){
if (j == " I like pancakes"){
j = " I don't like pancakes";
} else {
j = " I like pancakes";
}
document.getElementById("sentence").innerHTML=x+j;
}
</script>
</center>
</body>
</html>
it uses the innerHTML property to change the content
There was also another problem:
the write function were outside the function so it's never called

Categories

Resources