473,226 Members | 1,534 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,226 software developers and data experts.

Create Global Var in Function

I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:
<script language="JavaScript">

var variablesInUrl;
var vArray = new Array();

function loadUrlVariables()
{
varString = location.search;
//removes ? from varString
varString = varString.substring(1,varString.length);
//split into array containing variable=value
variableArray = varString.split('&');
variablesInUrl = variableArray.length-1

for (i=0; i<= variablesInUrl ; i++)
{
temp = variableArray[i].split("=");
vArray[i] = new Array();
vArray[i][0] = temp[0];
vArray[i][1] = temp[1];
}
}

//function returns variable's value
function getValue(varName)
{
for (i=0; i<=variablesInUrl; i++)
{
if (vArray[i][0] == varName)
return vArray[i][1]
}
alert ("Variable: "+varName+" was not found.")
}

loadUrlVariables()

//get value of a variable named step
alert( getValue("weight") )

</script>

This works but in order to get the value of the variable, I have to use
the getValue function. What I would really like is for the
loadUrlVariables function to create global variables out of the
variables present in the URL. This way I could just access them
normally (i.e. alert(weight) would display the value in the variable
weight). I was reading some and tried a test. Inside of the
loadUrlVariables I put
var testGlobal = document.body
testGlobal = "Am I a Global Variable"

then after my other alert, I did alert(testGlobal), but I got an
testGlobal is undefined error. So how do I make a global variable from
inside a function?

On an unrelated note:
In javascript, after each line are you suppose to put a ;? I see some
scripts that have a semi colon after each line and some that don't. I
haven't notice that it makes any different, but am wondering what the
technically right way is to do it?

Thanks,
Andrew V. Romero

Jul 20 '05 #1
4 24133
I should have mentioned that I would like the function to create global
variables out of each variable in the URL automatically. So I want
vArray[i][0] to be the name of the first global variable and
vArray[i][1] to be its value, etc. Let's pretend I don't know the names
of the variables before hand (i.e. I can not just say
weight=vArray[i][1]. I am aware of the possible naming conflicts that
may arise due to this.

Thanks,
Andrew V. Romero

Andrew V. Romero wrote:
I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:
<script language="JavaScript">

var variablesInUrl;
var vArray = new Array();

function loadUrlVariables()
{
varString = location.search;
//removes ? from varString
varString = varString.substring(1,varString.length);
//split into array containing variable=value
variableArray = varString.split('&');
variablesInUrl = variableArray.length-1

for (i=0; i<= variablesInUrl ; i++)
{
temp = variableArray[i].split("=");
vArray[i] = new Array();
vArray[i][0] = temp[0];
vArray[i][1] = temp[1];
}
}

//function returns variable's value
function getValue(varName)
{
for (i=0; i<=variablesInUrl; i++)
{
if (vArray[i][0] == varName)
return vArray[i][1]
}
alert ("Variable: "+varName+" was not found.")
}

loadUrlVariables()

//get value of a variable named step
alert( getValue("weight") )

</script>

This works but in order to get the value of the variable, I have to use
the getValue function. What I would really like is for the
loadUrlVariables function to create global variables out of the
variables present in the URL. This way I could just access them
normally (i.e. alert(weight) would display the value in the variable
weight). I was reading some and tried a test. Inside of the
loadUrlVariables I put
var testGlobal = document.body
testGlobal = "Am I a Global Variable"

then after my other alert, I did alert(testGlobal), but I got an
testGlobal is undefined error. So how do I make a global variable from
inside a function?

On an unrelated note:
In javascript, after each line are you suppose to put a ;? I see
some scripts that have a semi colon after each line and some that
don't. I haven't notice that it makes any different, but am wondering
what the technically right way is to do it?

Thanks,
Andrew V. Romero


Jul 20 '05 #2
In article <3F**************@icqmail.com>, rr*******@icqmail.com
enlightened us with...
I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:


Use this technique. It's easier to get them when you want them.

var paramArray = new Array();

function getParams()
{
// split the query string into param=val pieces
var qs = location.search.substr(location.search.indexOf("?" )+1);
qs = qs.split("&");
// split param and value into individual pieces
for (var i=0; i<qs.length; i++)
{
tmp = qs[i].split("=");
paramArray[tmp[0]] = tmp[1];
}
}

Now you can just do paramArray["myParam"] to get the value of myParam.
See example here.
http://www.ipwebdesign.net/kaelisSpa..._parseUrl.html

--
-------------------------------------------------
~kaeli~
There is no justification or rationalization
for mutilation. Ban declawing as inhumane.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace
-------------------------------------------------
Jul 20 '05 #3
"Andrew V. Romero" <rr*******@icqmail.com> writes:
I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:

<script language="JavaScript">
<script type="text/javascript">

In HTML 4, the language attribute is deprecated, and the type
attribute is mandatory
variablesInUrl = variableArray.length-1
bad naming, since there are "variableArray.length" variables in the URL,
not one less.

.... This works but in order to get the value of the variable, I have to
use the getValue function. What I would really like is for the
loadUrlVariables function to create global variables out of the
variables present in the URL.
Don't do that. Creating global variables gives too big a chance of
overwriting something important (e.g., if one of the variables
was called "window" or "document", then you would be in trouble).
This way I could just access them
normally (i.e. alert(weight) would display the value in the variable
weight). I was reading some and tried a test. Inside of the
loadUrlVariables I put

var testGlobal = document.body
"var" declares a local variable if used inside a function. It declares
a global variable if used outside of a function.
testGlobal = "Am I a Global Variable"

then after my other alert, I did alert(testGlobal), but I got an
testGlobal is undefined error. So how do I make a global variable
from inside a function?
You don't write "var" in front.

If you just write:

foo = 42;

and "foo" is not declared as a local variable, then it will be created
as a global variable.

You can also create global variables as properties of the global object.
The global variable "window" is a reference to the global object, so writing

window["foo"] = 42;

will also create a global variable called "foo".
Still, I suggest that you create just one global variable and use
the to store the rest:

---

var variables={}; // global variable referencing empty object
function loadURLVariables() {
var searchPairs = location.search.substring(1).split("&");
for (var i in searchPairs) {
var pair = searchPairs[i].split("=");
variables[pair[0]]=unescape(pair[1].replace(/\+/g," "));
/* if this is the result of a form action */
}
}

---

Then you can run "loadURLVariables()" and afterwards, you can refer to the
variables as

variables.foo

or

variables["foo"]

without clobbering the global scope with too many variables.
On an unrelated note:
In javascript, after each line are you suppose to put a ;? I
see some scripts that have a semi colon after each line and
some that don't. I haven't notice that it makes any
different, but am wondering what the technically right way is
to do it?


Each statement ends in a semicolon, but in some cases the semicolon can
be omitted and is then automatically inserted by the Javascript parser.
That is called "semicolon insertion". In other cases, omitting the
semicolon gives an error.

In practice, it is much simpler *and safer* not to worry about it, and
*always* end ones statements with a semicolon, and not let statements
spanning more than one line have lines ending where a semicolon would
make sense.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
Thanks everyone for the comments, they have really helped get me over
this hurdle in Javascript.

Lasse Reichstein Nielsen wrote:
"Andrew V. Romero" <rr*******@icqmail.com> writes:

I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:

<script language="JavaScript">

<script type="text/javascript">

In HTML 4, the language attribute is deprecated, and the type
attribute is mandatory

variablesInUrl = variableArray.length-1

bad naming, since there are "variableArray.length" variables in the URL,
not one less.

...
This works but in order to get the value of the variable, I have to
use the getValue function. What I would really like is for the
loadUrlVariables function to create global variables out of the
variables present in the URL.

Don't do that. Creating global variables gives too big a chance of
overwriting something important (e.g., if one of the variables
was called "window" or "document", then you would be in trouble).

This way I could just access them
normally (i.e. alert(weight) would display the value in the variable
weight). I was reading some and tried a test. Inside of the
loadUrlVariables I put

var testGlobal = document.body

"var" declares a local variable if used inside a function. It declares
a global variable if used outside of a function.

testGlobal = "Am I a Global Variable"

then after my other alert, I did alert(testGlobal), but I got an
testGlobal is undefined error. So how do I make a global variable
from inside a function?

You don't write "var" in front.

If you just write:

foo = 42;

and "foo" is not declared as a local variable, then it will be created
as a global variable.

You can also create global variables as properties of the global object.
The global variable "window" is a reference to the global object, so writing

window["foo"] = 42;

will also create a global variable called "foo".
Still, I suggest that you create just one global variable and use
the to store the rest:

---

var variables={}; // global variable referencing empty object
function loadURLVariables() {
var searchPairs = location.search.substring(1).split("&");
for (var i in searchPairs) {
var pair = searchPairs[i].split("=");
variables[pair[0]]=unescape(pair[1].replace(/\+/g," "));
/* if this is the result of a form action */
}
}

---

Then you can run "loadURLVariables()" and afterwards, you can refer to the
variables as

variables.foo

or

variables["foo"]

without clobbering the global scope with too many variables.

On an unrelated note:
In javascript, after each line are you suppose to put a ;? I
see some scripts that have a semi colon after each line and
some that don't. I haven't notice that it makes any
different, but am wondering what the technically right way is
to do it?

Each statement ends in a semicolon, but in some cases the semicolon can
be omitted and is then automatically inserted by the Javascript parser.
That is called "semicolon insertion". In other cases, omitting the
semicolon gives an error.

In practice, it is much simpler *and safer* not to worry about it, and
*always* end ones statements with a semicolon, and not let statements
spanning more than one line have lines ending where a semicolon would
make sense.

/L


Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: lkrubner | last post by:
I have a webserver through Rackspace. I create a domain. I create an FTP user. I upload some files. I create a database called testOfSetupScript and then I create a database user named setup. I...
22
by: nobody | last post by:
hello everybody, is there a way of creating an array with help of a function that would accept the name of this array as a parameter and then create global Array type variable of that name? so...
8
by: Steve Neill | last post by:
Can anyone suggest how to create an arbitrary object at runtime WITHOUT using the deprecated eval() function. The eval() method works ok (see below), but is not ideal. function Client() { }...
2
by: Chris LaJoie | last post by:
The code below creates a thread on a global function (ReadChildOutput): CreateThread(NULL, 0, ReadChildOutput, (LPVOID)this, 0, &ThreadId); How would I create a thread on a non-global function,...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
3
by: Ralph | last post by:
Hi Is this possible? One thing I can do is create the global array and add the new item to it from inside the function but that's not what I'm looking for. Thank you Ralph
4
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is...
3
by: Beamer | last post by:
Hi I am trying to build a roating slide effect in javascript. Basically, I have a list like below <ul id="slideShowCnt"> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li...
17
by: DeZZar | last post by:
Hi all, I need to regularly backup my database as an Excel file and have been using the File Export option. Problem is I need anyone using the database to be able to do this easily - nopt...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.