user1976322
user1976322

Reputation: 37

Javascript not storing variables at all. Every variable "undefined"

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.

Upvotes: 1

Views: 105

Answers (4)

Darthg8r
Darthg8r

Reputation: 12685

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...

Upvotes: 2

beezir
beezir

Reputation: 460

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.

Upvotes: 4

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

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" 
}

Upvotes: 4

RyanFishman
RyanFishman

Reputation: 695

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

Upvotes: 5

Related Questions