1

I was wondering if anyone could help me. The problem is javascript isn't storing any variables and is acting up.

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

var name = document.getElementById('text_field').value;

var test = "foobar";


function test_function(){
alert("hello"+test);    
}

alert('test '+test);

</script>

The second alert doesnt happen at all, and when i click on the button to trigger the test_function() it alerts out "helloundefined" . I just don't know what to do, it was working fine then all of a sudden it stopped. I should mention that this is on a php page but that shouldn't make a difference.

1
  • 2
    Is your script on the very bottom of the body section? I bet that'll solve your issue. Commented Jan 14, 2013 at 3:35

4 Answers 4

5

If there is no element with the ID text_field, the rest of the code will not run.

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

1 Comment

To be clear, if the script throws an exception, the rest will not run, and the lack of a element with the ID text_field will throw an exception
4

try changing:

var name = document.getElementById('text_field').value;

to

var name = document.getElementById('text_field').value || "some default value;

OR

var name;
if(document.getElementById('text_field')) { 
  name = document.getElementById('text_field').value 
} else { 
  name = "some value" 
}

Comments

4

Without seeing the rest of the code, most likely the culprit is this line:

var name = document.getElementById('text_field').value;

If the script block is run before 'text_field' exists, you get an error and the rest of the javascript doesn't execute. The result is that you don't see the alert, and the test variable is never set. You need to call the code after the DOM exists, either by running it in onload (or a ready function in jQuery) or by putting the script block at the end of the page.

Comments

2

Move that script block to bottom of the page. text_field does not exist yet. If you're debugging in a browser, use Chrome or Firefox and make use of the "Console" window in the dev tool bar. It'll tell you things like this...

Comments

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.