Reputation: 3
In HTML form, I want to display the user input when a button is clicked. This is done by calling a JavaScript function. The user input is hold into a variable which then is used inside a function. The problem, the function doesn't recognize the var unless it's defined inside it.
The following is the HTML and JS code. To view (https://dl.dropboxusercontent.com/u/4301151/stackoverflow/varNoDefined.html)
<p><label>Name:</label>
<input type="text" name="userName" id="userName" placeholder="e.g John Lewis"/>
</p>
<input type="submit" name="submitButton" value="Display" onclick="run()"/>
<p>Name Provided: <label id="outputUserName"></label></p>
var userName = document.getElementById("userName").value;
function run() {document.getElementById("outputUserName").innerHTML = userName;}
It will work fine if I have the following inside the function:
document.getElementById("outputUserName").innerHTML = document.getElementById("userName").value;
or if I define the var inside the function
I need the var to be global so to use it with other functions and not define it so many times
Upvotes: 0
Views: 1145
Reputation: 816472
The problem, the function doesn't recognize the var unless it's defined inside it.
No that is not the problem. The variable is recognized, but it doesn't have the value you want.
You are trying to read the value of the input before the user typed anything. userName
will simply hold an empty string. You can easily verify this by giving the input a default value:
<input type="text" name="userName" id="userName" value="default value"/>
You have to read the value at the moment you need / want it. As compromise, you can keep a reference to the DOM element as global variable:
var userName = document.getElementById("userName");
function run() {
document.getElementById("outputUserName").innerHTML = userName.value;
}
Also relevant: Why does jQuery or a DOM method such as getElementById not find the element?
Upvotes: 2
Reputation: 840
Another issue is that you need to load the script tag after the body content or put all your code inside of an on ready function so that you know that the page has been rendered. With the script before the actual element, the lookup for document.getElementById("userName");
returns null because the element hasn't been rendered by the browser yet. If you look in your console you should see that.
Uncaught TypeError: Cannot read property 'value' of null
Upvotes: 0