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