2

I have a problem with a javascript global variable, let's suppose I have the following

var globalVar;

I have a text field

<input type="text" id="myInput" onkeydown="checkKey(this)" onkeypress="checkKey(this)"/>

And in the function checkkey, I assign some value to it:

globalVar=document.forms[0].elements("myInput").value;

I checked the the global variable value has changed with an alert. When I try to use globalVar in another function, I find it has the value undefined. The other function has something like:

param += globalVar;
Mansuro
  • 4,558
  • 4
  • 36
  • 76

1 Answers1

6

The elements property of form instances isn't a function, it's an object. Use

globalVar=document.forms[0].elements.myInput.value;

...or

globalVar=document.forms[0].elements["myInput"].value;

...but better yet, with the way you're calling checkKey, just declare an argument called input or whatever and use

globalVar=input.value;

...since you're passing this into checkKey.

If you're going to access the form field by its name as you have, use the name attribute rather than the id attribute (although id will work on many browsers as well).

If your var globalVar; is at global scope (outside of all functions), then it is a global variable. If that var statement is inside a function, it's a local variable. You haven't given us enough context to know where the var is, but if it's at global scope, and you successfully set its value, and later you check it, it will be set.

Live demo using the long form | Live demo using the argument

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875