2

I have this code:

var StateTextBox = document.getElementById("State");
function InitializeVP() {
  StateTextBox.value = "Test"
}

It can't find the StateTextBox as a variable... Does anyone know why?

When I do it like so:

function InitializeVP() {
  document.getElementById("State").value = "Test"
}

It works. Can anyone explain to me what I am doing wrong please?

1
  • Your code works just fine: jsfiddle.net/YWgvv (As long as you run it after the DOM has been loaded). We'll need more code before we can tell you what is wrong. Commented Nov 18, 2012 at 3:22

2 Answers 2

2

When are you attempting to set the StateTextBox variable? Chances are, it is attempting to be set in the head section, and in that case, the element will not be set.

Try putting it just before the closing </body> tag, and it will probably work there (you can leave your InitializeVP() function at the top.

Even better? Use jQuery with the $(document).ready, and you are pretty much guaranteed that your variable will be initialized.

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

2 Comments

Yeah its for college...we can't use anything but JavaScript....my professor doesn't even teach. He has a phd in Math...
@heinst It's not too bad; it's far better to learn JavaScript than it is to develop a dependency on jQuery and similar tools.
0

You probably have the code in the wrong order. Your reference elements that you are referring to do not exist....yet.

1 Comment

The order of the code provided here doesn't have an affect on the outcome, given scope and hoisting. You're probably right though that this code is being ran prior to the DOM elements existing.

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.