I recently started to learn Javascript and have prior experience in server side languages such as PHP. The issue I'm having is that I cannot use variables that are defined outside of a function inside the function. I always have to copy the variable into the function in order to get my code to work. I will post an example below.
var first = document.getElementById("first");
var second = document.getElementById("second");
function add () {
alert(Number(first.value) + Number(second.value));
}
1 Answer 1
Most likely the problem is that your script is being executed when the page is still being loaded, and before the "first" and "second" elements have been created.
Accessing the variables works fine. They just happen to be initialized to "undefined" at the time they are created. Moving the variables inside the function means that they aren't initialized until the function is called, which is after the page has been completely loaded.
add
before the variables are set, and do those elements actually exist and have a value?<script>
tags are called in the<head>
which would explain this. Stupid question and I will delete it soon.