Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access global variables (Javascript)

Tags:

javascript

var hours = document.getElementById("hrs").value; // Global variables declared
var mins = document.getElementById("min").value; 
var seconds = document.getElementById("sec").value; 

function random()
{
    alert(hours);
    alert(mins);
    alert(seconds);
}

The output results as undefined in all 3 cases.

like image 560
scorpio98 Avatar asked Dec 30 '13 07:12

scorpio98


People also ask

What are the problems with global variables in JavaScript?

This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn't overwrite values of another variable. On the usage of more global variables in our code, it may lead to a maintenance issue.

Why is my global variable undefined JavaScript?

The reason the first alert is undefined is because you re-declared global as a local variable below it in the function. And in javascript that means from the top of the function it is considered the local variable.

Can you set global variables in JavaScript?

Global ScopeGlobal variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.


2 Answers

This particular code might be within the body of the HTML file and this code is executed before the particular HTML elements are created. So, the the value undefined is assigned to those values.

So, you might want to move the value assignment part within the function itself.

var hours, mins, seconds;

function random()
{
    hours = document.getElementById("hrs").value;
    mins = document.getElementById("min").value; 
    seconds = document.getElementById("sec").value; 

    alert(hours);
    alert(mins);
    alert(seconds);
}

Note 1: Normally, if you don't use a library like jQuery, code like this is put in onload. This is what MDN has to say about, when onload is triggered

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

So, if you are getting values from the HTML elements, you might want to make sure that we fetch values from them only after the HTML document is completed loaded.

Note 2: Apart from this, you might want to check if you have really set the id of the HTML elements with hrs, min and sec properly. name and id attributes are actually used for different purposes.

like image 182
thefourtheye Avatar answered Oct 17 '22 09:10

thefourtheye


I had a similar issue recently on a server side script.

This was because I was redeclaring the variable inside the function using var. Getting rid of var fixed the issue.

like image 28
Guillaume Renoult Avatar answered Oct 17 '22 09:10

Guillaume Renoult