Reputation: 3
I recently created an input box in HTML:
<input type="number" id="aa" onchange="yy()">
<p id="xx"></p>
Then I called the following code:
var gg = document.getElementById("aa").value;
function yy(){
document.getElementById("xx").innerHTML = gg;
}
Nothing appeared.
However if I change the script into:
function yy(){
gg = document.getElementById("aa").value;
document.getElementById("xx").innerHTML = gg;
}
It worked!
I thought that if I declared the variable gg
first (global), I could use the value in the yy
function. Why does the first code not behave like the second code?
Upvotes: 0
Views: 307
Reputation: 7299
Thats because you didn't put the value inside the function. Now var gg
will always hold the initial value. Which is on page load empty.
By putting it inside the function. The value will be retrieved as soon as the function gets triggered. In your case, you putted a onchange
trigger on it.
So when the value changes, the function will run at that moment, and retrieves the value inside the input field.
You can only get something if you ask for it. Or in this case JavaScript can only get something if something asks for it
Your function in the first case doens't ask for a value. In your seconds case, JavaScript
asks the value
of element #aa
Upvotes: 1
Reputation: 30739
You can still use gg
inside yy
function. But the thing here is the value you have inside gg
. Since you are calling
var gg = document.getElementById("aa").value;
on page load, the input element do not have any value so the value of gg
is always blank. And now when you change the value for id="aa"
you are using the value of gg
for its innerHTML
and you always get blank. Now, the only fix is that, since your innerHTML
depends on value of gg
(Which is for input with id aa), you must include this inside your change()
function to get correct output. Thus, the reason is not that you cannot access or get the value of global variable- you can but in this case the value is incorrect as expected.
For proper verification and understanding here is an example that has the value of id='aa'
already specified then when you change the input then you get to see the value of gg
:
var gg = document.getElementById("aa").value;
function yy(){
document.getElementById("xx").innerHTML=(gg);
}
<input type="number" id="aa" onchange="yy()" value='123'>
<p id="xx"></p>
Upvotes: 0