Link to home
Start Free TrialLog in
Avatar of John500
John500Flag for United States of America

asked on

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
Avatar of hielo
hielo
Flag of Wallis and Futuna image

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

Avatar of John500

ASKER

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
Avatar of John500

ASKER

I forgot to mention, the js file will be called from an HTML page.

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" :)

Avatar of John500

ASKER

>>  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!
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).
Avatar of John500

ASKER

>>  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.

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".
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of John500

ASKER

>>  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
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.
Avatar of John500

ASKER

Thanks