Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

How to deal with global variables in a js file

The js code below needs to be included within a js file which has various functions.  I've been asked to put all the variables seen below inside the functions (starting with var options...) .

Two questions:

1)  I looked at the destination js file and there are no variables at all using the method of:

var options ...

The only variables I see are 'input' parameters to the functions.  Thus, can't I just add these variables to the top of the destination js file?

2)  If I need to put them inside the functions themselves, how should I do this seeing both functions need the values from the other function?

The output of this code is seen the picture below

Thanks!
<head>
<title>Chain Select</title>
<script>
var options=new Array();
options[0]=new Array();
options[0]['myoptions']='Option_1';
options[0]['sub_options']=['html_link_1','html_link_2','html_link_3','html_link_4'];
options[1]=new Array();
options[1]['myoptions']='Option_2';
options[1]['sub_options']=['html_link_5','html_link_6','html_link_7','html_link_8'];
function initBoxes(box1,box2) {
var myoptions=document.getElementById(box1);
var subOptions=document.getElementById(box2);
for (i=0; i<options.length; i++) {
  var x=document.createElement('option');
  var y=document.createTextNode(options[i]['myoptions']);
  if (window.attachEvent) { // for IE
  x.setAttribute('value',y.nodeValue);
  }
  x.appendChild(y);
  myoptions.appendChild(x);
}

myoptions.onchange=function() {
  if(this.value!="") {
   var list=document.getElementById(box2);
   while (list.childNodes[0]) {
    list.removeChild(list.childNodes[0])
   }
   fillBox2(subOptions,this.value);
   }
  }

fillBox2(subOptions,myoptions.value);
}
function fillBox2(box2,myoptions) {
for (i=0; i<options.length; i++) {
  if (options[i]['myoptions']==myoptions) {
   var sub_options=options[i]['sub_options'];
  }
}
for (i=0; i<sub_options.length; i++) {
  var x=document.createElement('option');
  var y=document.createTextNode(sub_options[i]);
  x.appendChild(y);
  box2.appendChild(x);
  }
} 
window.onload=function() {initBoxes('myoptions','subOptions');} 
</script>
</head>

<body>

<form method="post" action="#">
<p>
  <label>Select Options: 
  <select id="myoptions" name="myoptions">
</select></label>
<label>Select Sub Options: 
<select id="subOptions" name="subOptions">
</select></label></p>
</form>
</body>
</html>

Open in new window

html-code-example.JPG
0
John500
Asked:
John500
  • 6
  • 6
1 Solution
 
hieloCommented:
provide an options parameter to the functions and pass it around among them. You initialize your options array upon load:
<head>
<title>Chain Select</title>
<script>
function initBoxes(box1,box2,options) {
	var myoptions=document.getElementById(box1);
	var subOptions=document.getElementById(box2);
	for (var i=0; i<options.length; i++) {
  		var x=document.createElement('option');
  		var y=document.createTextNode(options[i]['myoptions']);
  		if (window.attachEvent) { // for IE
  			x.setAttribute('value',y.nodeValue);
  		}
  		x.appendChild(y);
  		myoptions.appendChild(x);
	}

	myoptions.onchange=function() {
  		if(this.value!="") {
   			var list=document.getElementById(box2);
   			while (list.childNodes[0]) {
    			list.removeChild(list.childNodes[0])
   			}
   			fillBox2(subOptions,this.value,options);
   		}
  	}

	fillBox2(subOptions,myoptions.value,options);
}

function fillBox2(box2,myoptions, options) {
	for (var i=0; i<options.length; i++) {
  		if (options[i]['myoptions']==myoptions) {
   			var sub_options=options[i]['sub_options'];
  		}
	}

	for (var i=0; i<sub_options.length; i++) {
  		var x=document.createElement('option');
  		var y=document.createTextNode(sub_options[i]);
  		x.appendChild(y);
  		box2.appendChild(x);
  	}
} 

window.onload=function() {
	//now options is no longer global.
    var options=new Array();
    options[0]=new Array();
    options[0]['myoptions']='Option_1';
    options[0]['sub_options']=['html_link_1','html_link_2','html_link_3','html_link_4'];
    options[1]=new Array();
    options[1]['myoptions']='Option_2';
    options[1]['sub_options']=['html_link_5','html_link_6','html_link_7','html_link_8'];

	initBoxes('myoptions','subOptions',options);
} 
</script>
</head>

<body>

<form method="post" action="#">
<p>
  <label>Select Options: 
  <select id="myoptions" name="myoptions">
</select></label>
<label>Select Sub Options: 
<select id="subOptions" name="subOptions">
</select></label></p>
</form>
</body>
</html>

Open in new window

0
 
John500Author Commented:
hielo,

Thanks for the input.  

One thing I'm still unsure about is why all the other functions in the js file don't have the <script> tag around them... or is the entire file with all the functions surrounded by one tag?  I don't have the file on me so I forget.

If there is not a tag around the functions in that file, won't these lines be floating out there:

 var options=new Array();
    options[0]=new Array();
    options[0]['myoptions']='Option_1';
    options[0]['sub_options']=['html_link_1','html_link_2','html_link_3','html_link_4'];
    options[1]=new Array();
    options[1]['myoptions']='Option_2';
    options[1]['sub_options']=['html_link_5','html_link_6','html_link_7','html_link_8'];

... Also, you do realize that this call will not be part of the js file:

window.onload=function()....

Can you show your solution as if the two functions above were in the js file?

Thanks
0
 
John500Author Commented:
I forgot to mention, the js file will be called from an HTML page.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
hieloCommented:

One thing I'm still unsure about is why all the other functions in the js file don't have the <script> tag around them...
you need the <script> tags only if you are putting javascript code in an "HTML" file. A javascript file should NOT contain any <script> tags around the javascript code.

or is the entire file with all the functions surrounded by one tag?
If it helps you, imagine the script tags on a javascript file are already there, but are "invisilble" :)

0
 
John500Author Commented:
>>  If it helps you, imagine the script tags on a javascript file are already there, but are "invisilble" :)

Yes, I agree with you.  I did not really feel there were any tags at all and I knew for certain that tags were used within an HTML file.

Thus, I was wondering why you included them in your answer.   Can you tell me how to work this solution within the js file?  The code you provided is for the HTML file.

Thanks!
0
 
hieloCommented:
Thus, I was wondering why you included them in your answer.
I gave you an html file so you can copy and paste onto your notepad, save it as test.html and try it out. If it does what you want, you can just "extract" the stuff between the script tags and append it to you js file (WITHOUT the script tags).
0
 
John500Author Commented:
>>  you can just "extract" the stuff between the script tags and append it to you js file (WITHOUT the script tags).

Putting the functions in the js file was not an issue for me.  This question has been about the variables and how to handle them and them alone.  If I understood the requirement (and I'm sure I do now) the variables are not to be global in the js file.

How are you dealing with the variables in your solution as they pertain to the js file.  Forget the HTML file, I don't even want to consider it.  As it looks now, the variables in your solution are just floating out there attached to nothing, right ?

Thanks.
0
 
hieloCommented:

As it looks now, the variables in your solution are just floating out there attached to nothing, right ?
Of course NOT. Currently there's:
window.onload=function(){...} //this function is an "anonymous function".

the options variable exists ONLY in THAT anonymous function, so they are not "global".
0
 
hieloCommented:
If it helps you understand it better, give the function a name and set the onload to it:
window.onload=start;

function start() {
	//now options is no longer global.
    var options=new Array();
    options[0]=new Array();
    options[0]['myoptions']='Option_1';
    options[0]['sub_options']=['html_link_1','html_link_2','html_link_3','html_link_4'];
    options[1]=new Array();
    options[1]['myoptions']='Option_2';
    options[1]['sub_options']=['html_link_5','html_link_6','html_link_7','html_link_8'];

	initBoxes('myoptions','subOptions',options);
}

Open in new window

0
 
John500Author Commented:
>>  give the function a name and set the onload to it

I think your suggestion is closer.  I failed to mention that the existing js file is called and handled without the use of 'window.onload'

My original post was vague and I intended only to illustrate what I currently had in place within the HTML file.  I should have mentioned the requirement was not only to put all the code into a specific js file but also that the existing js file functions were being called first (before my functions) for other reasons.   My code would just be tacked on the end of the file.

That left me wondering about the variables since I was asked to put them within the functions.  I guess I can use your last post except without the call to 'window.onload'

This however, leaves me wondering how 'function start() ' will be triggered since the existing js functions are called first.

Any ideas there ?

Thanks
0
 
hieloCommented:
the initBoxes function depends on the <SELECT> lists. So you have to call start() upon load. So include:
window.onload=start;

in the js file. IF you are already calling some other function at onload, then on THAT function you just call:
start();

explicitly at the end of it.
0
 
John500Author Commented:
Thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 6
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now