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;
The
elementsproperty offorminstances isn’t a function, it’s an object. Use…or
…but better yet, with the way you’re calling
checkKey, just declare an argument calledinputor whatever and use…since you’re passing
thisintocheckKey.If you’re going to access the form field by its name as you have, use the
nameattribute rather than theidattribute (althoughidwill 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 thatvarstatement is inside a function, it’s a local variable. You haven’t given us enough context to know where thevaris, 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