|
Subject:
|
Javascript Scope of Variables.
|
|
Posted By:
|
minhtam
|
Post Date:
|
1/7/2006 3:49:39 AM
|
--- In one HTML file, I have the following section of Javascript code with a global variable "speclist" that is to be accessed inside a Javascript function. The problem: it seems that the function doesn't see the global variable. Did I overlook something really easy? It would work if the variable is declared locally in the function.
Code listing of what doesn't work: <script type="text/javascript"> var speclist=document.svcSearch.specialty // global variable function updateSpecialty(selectedProviderIndex) { // var speclist=document.svcSearch.specialty -- works if declared locally speclist.options.length=0 //clear list if (selectedProviderIndex > 0) { for (i=0; i < specs[selectedProviderIndex].length; i++) { speclist.options[speclist.options.length] = new Option(specs[selectedProviderIndex][i].split("|")[0], specs[selectedProviderIndex][i].split("|")[1]) } } } </script> --- and later followed by HTML <select name="svcProvider" size="6" id="svcProvider" onchange="updateSpecialty(this.selectedIndex)"> <option >a</option> <option >b</option> </select>
I would greatly appreciate any feedback. Thank you.
|
|
Reply By:
|
interrupt
|
Reply Date:
|
1/7/2006 7:18:01 AM
|
Is svcSearch your form name, and specialty the name of the dropdown? Just wondering if its a simple error like spelling. Can you post the complete code?
Joe
|
|
Reply By:
|
minhtam
|
Reply Date:
|
1/7/2006 9:27:43 PM
|
Yes, the form id is "svcSearch" and the select box to be filled out by Javascript is named "specialty" as shown below. The problem is that the global var speclist isn't seen by the function updateSpecialty. It works if declared locally, meaning that spelling isn't the problem. Thanks for looking at this with me.
<script type="text/javascript"> var speclist=document.svcSearch.specialty // global variable function updateSpecialty(selectedProviderIndex) { // var speclist=document.svcSearch.specialty -- works if declared locally var specs=new Array(); specs[0]="" specs[1]=["X1|x1", "Y1|y1"] specs[2]=["X2|x2", "Y2|y2"]
speclist.options.length=0 //clear list if (selectedProviderIndex > 0) { for (i=0; i < specs[selectedProviderIndex].length; i++) { speclist.options[speclist.options.length] = new Option(specs[selectedProviderIndex][i].split("|")[0], specs[selectedProviderIndex][i].split("|")[1]) } } } </script> --- and later followed by HTML <form id="svcSearch" name="svcSearch" method="post" action="Results.php">
<select name="svcProvider" size="6" id="svcProvider" onchange="updateSpecialty(this.selectedIndex)"> <option>a</option> <option>b</option> </select>
<select name="specialty" size="6" multiple="multiple" id="specialty"> <!-- options filled out by JavaScript --> </select>
<input type="submit" name="Find" value="Find"/>
</form>
|