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;

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I said it's a global variable, so it is at global score(outside all functions)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.